/**
 * V2.0
 * 增加虚拟工单功能
 * 增加产能分摊，班制可以自定义，不限制与两班制
 * 砂型排序恢复按天排序
 * 自动排序功能：修定为按时间分摊
 * 新增工单锁定功能
 * 修订: 读取原计划和读当前计划判断的时候没有考虑到虚拟工单的问题
 */
 function cp_man() {

	/**
	 * 数组去重
	 * **/
	Array.prototype.distinct = function () {
		var arr = this,
			result = [],
			i,
			j,
			len = arr.length;
		for (i = 0; i < len; i++) {
			for (j = i + 1; j < len; j++) {
				if (arr[i] === arr[j]) {
					j = ++i;
				}
			}
			result.push(arr[i]);
		}
		return result;
	}

	/**
	 * 筛选Json数据
	 **/
	function filterData(data, filter) {
		return data.filter(item => {
			var isIn = true
			for (var key in filter) {
				if (filter[key].indexOf(item[key]) < 0) {
					isIn = false
					break
				}
			}
			return isIn
		})
	}

	/*
	* @description    根据某个字段实现对json数组的排序
	* @param   array  要排序的json数组对象
	* @param   field  排序字段（此参数必须为字符串）
	* @param   reverse 是否倒序（默认为false）
	* @return  array  返回排序后的json数组
	* Jsong数据分组排序
	*/
	function JsonArrayGroup(arr) {
		let map = {}, dest = [], date_ary = {};
		for (let i = 0; i < arr.length; i++) {
			var ai = arr[i];
			if (!map[ai.Resource_ID]) {
				dest.push({
					Resource_ID: ai.Resource_ID,
					Resource: ai.Resource,
					data: []
				});
				map[ai.Resource_ID] = ai;
				date_ary = []
			} else {
				for (let j = 0; j < dest.length; j++) {
					let dj = dest[j];
					if (dj.Resource_ID == ai.Resource_ID) {
						if (date_ary[ai.Date] == null) {
							date_ary[ai.Date] = ai;
							dj.data.push(ai);
						}
						break;
					}
				}
			}
		}
		return dest;
	}
	/**
	 * 给某个日期增加n天
	 * 
	*/
	function addDate(date, days) {
		if (days == undefined || days == '') {
			days = 1;
		}
		var date = new Date(date);
		date.setDate(date.getDate() + days);
		var month = date.getMonth() + 1;
		var day = date.getDate();
		return date.getFullYear() + '-' + getFormatDate(month) + '-' + getFormatDate(day);
	}
	// 日期月份/天的显示，如果是1位数，则在前面加上'0'
	function getFormatDate(arg) {
		if (arg == undefined || arg == '') {
			return '';
		}
		var re = arg + '';
		if (re.length < 2) {
			re = '0' + re;
		}
		return re;
	}
	let lockStore = Ext.create('Ext.data.Store', {
		fields: ['Resource_ID', 'Date', 'Scheduling'],
		data: []
	});
	function AssessmentOfHours(source, w_shift, WIP_ID) {
		/**
		* 临时表:用于存储班次分摊时的临时数据
		* 日期:date
		* 班次:bc
		* 班次总工时:wrkhour1
		* 班次已分配工时:wrkhour2
		* 班次可用工时:wrkhour3
		**/
		let TempListWrkHour = [];
		/**
		 * 班制总工时
		 **/
		let shift_hour = 0;
		if (w_shift.length > 0) {
			shift_hour = w_shift[0].OneWorkTime + w_shift[0].TwoWorkTime + w_shift[0].ThreeWorkTime + w_shift[0].FourWorkCapacity
		}

		var Effective_Time_Arr = BS_Work_Shift_Effective_Time.filter(function (p) {
			if (p.Work_Noid === w_shift[0].Work_Noid) {
				if (p.Sign_No % 2 != 0) {
					return p;
				}
			}
		});
		/**
		 * 根据签到类型返回对应的工时
		 **/
		function TempReturnWorkTime(Sign_No) {
			switch (Sign_No) {
				case "1" || "2":
					return w_shift[0].OneWorkTime;
					break;
				case "3" || "4":
					return w_shift[0].TwoWorkTime;
					break;
				case "5" || "6":
					return w_shift[0].ThreeWorkTime;
					break;
				case "7" || "8":
					return w_shift[0].FourWorkCapacity;
					break;
				default: return '0';
			}
		}
		/**
		 * 遍历虚拟工单做提前扣减
		 **/
		foreach(source, function (el) {
			if (el.GcdType == 4) {
				let Time_Arr = filterData(Effective_Time_Arr, { BcType: [el.Scheduling] });
				let flg = 0;
				let wrkhr = Time_Arr.length > 0 ? TempReturnWorkTime(Time_Arr[0].Sign_No) : 0;
				let month = new Date(el.Date).getMonth() + 1;
				let day = new Date(el.Date).getDate();
				let str = new Date(el.Date).getFullYear() + '-' + getFormatDate(month) + '-' + getFormatDate(day);
				let rows = filterData(TempListWrkHour, { date: [str.replace(/\"/g, "")], bc: [el.Scheduling] });
				foreach(lockStore.getData().items, function (p) {
					let __el = p.data;
					let ___month = new Date(__el.Date).getMonth() + 1;
					let ___day = new Date(__el.Date).getDate();
					let ___str = new Date(__el.Date).getFullYear() + '-' + getFormatDate(___month) + '-' + getFormatDate(___day);
					if (__el.Resource_ID != WIP_ID && str.replace(/\"/g, "") != ___str && __el.Scheduling != el.BcType && __el.Lock != 1) {
						flg = 1;
					}
				});
				if (flg == 1) {
					if (rows.length == 0) {
						let obj = new Object();
						obj.date = str;
						obj.bc = el.Scheduling;
						obj.wrkhour1 = wrkhr;
						obj.wrkhour2 = wrkhr - el.PlanDate;
						obj.wrkhour3 = el.PlanDate;
						TempListWrkHour.push(obj);
					} else {
						rows[0].wrkhour1 = wrkhr;
						rows[0].wrkhour2 = rows[0].wrkhour2 - el.PlanDate;
						rows[0].wrkhour3 = rows[0].wrkhour3 + el.PlanDate;
					}
				}
			}
		});
		temp = []; bc_temp = [];
		var month = new Date().getMonth() + 1;
		var day = new Date().getDate();
		var str = new Date().getFullYear() + '-' + getFormatDate(month) + '-' + getFormatDate(day);
		let myDate = JSON.stringify(str);
		var bc = 0;
		/**
		 *修改当前行工单数据 
		 **/
		let editSoucre = function (item, BcType, index, days) {
			if (item.Lock == 0) {
				item.Date = getTop().wijmo.Globalize.parseDate(new Date(addDate(myDate.substring(1, myDate.length - 1), days)).format('yyyy/MM/dd'), 'yyyy/MM/dd');
				item.ScheduleEndDate = getTop().wijmo.Globalize.parseDate(new Date(myDate).format('yyyy/MM/dd'), 'yyyy/MM/dd');
				item.Scheduling = BcType;
				item.index = index;
			}
		}
		foreach(source, function (item, i) {
			if (item.Resource_ID == WIP_ID) {
				if (Effective_Time_Arr.length > 0) {
					if (item.GcdType == 4 || item.Lock == 1) { return; }

					let el = Effective_Time_Arr[bc];
					var Time_Arr = filterData(Effective_Time_Arr, { BcType: [el.BcType] });

					let wrkhr = Time_Arr.length > 0 ? TempReturnWorkTime(el.Sign_No) : 0;
					let days = parseInt(item.PlanDate / shift_hour);
					let hrs = Math.round((item.PlanDate % shift_hour) * 100) / 100;
					let hrs_ye = 0;
					wrkhr = Math.round(wrkhr * 100) / 100;
					console.log('工时换算为：n天h小时');
					console.log(days + '天；' + hrs + '小时');
					console.log('----------工时换算完成---------------');

					foreach(lockStore.getData().items, function (p) {
						let __el = p.data;
						let month = new Date(__el.Date).getMonth() + 1;
						let day = new Date(__el.Date).getDate();
						let str = new Date(__el.Date).getFullYear() + '-' + getFormatDate(month) + '-' + getFormatDate(day);
						if (__el.Resource_ID == WIP_ID && myDate.replace(/\"/g, "") == str && __el.Scheduling == el.BcType && __el.Lock == 1) {

							let rows = filterData(TempListWrkHour, { date: [str.replace(/\"/g, "")], bc: [__el.Scheduling] });
							if (bc + 1 == w_shift[0].Work_Type) {
								if (rows.length == 0) {
									myDate = JSON.stringify(addDate(myDate.substring(1, myDate.length - 1), 1));
									bc = 0;
								}
							} else {
								if (rows.length == 0) {
									bc = bc + 1;
									el = Effective_Time_Arr[bc];
								}
							}
						}
					});
					let tempObj = new Object();

					let rows = filterData(TempListWrkHour, { date: [myDate.replace(/\"/g, "")], bc: [el.BcType] });

					if (rows.length == 0) {
						tempObj.date = myDate.replace(/\"/g, "");
						tempObj.bc = el.BcType;
						tempObj.wrkhour1 = Number(wrkhr);
						tempObj.wrkhour2 = Number((wrkhr - item.PlanDate).toFixed(2));
						tempObj.wrkhour3 = Math.round(item.PlanDate * 100) / 100;

						if (days > 0) {
							myDate = JSON.stringify(addDate(myDate.substring(1, myDate.length - 1), days));
							tempObj.date = myDate.replace(/\"/g, "");
						}
						if (hrs >= wrkhr) {
							hrs_ye = hrs - wrkhr;
							while (hrs_ye >= wrkhr) {
								if (bc + 1 == w_shift[0].Work_Type) {
									tempObj.bc = Effective_Time_Arr[0].BcType;
									tempObj.wrkhour1 = Number(wrkhr);
									tempObj.wrkhour2 = Number((hrs_ye - wrkhr).toFixed(2));
									tempObj.wrkhour3 = Math.round(hrs_ye * 100) / 100;
									hrs_ye = hrs_ye - wrkhr;
									bc = 0;
									el = Effective_Time_Arr[bc];
									myDate = JSON.stringify(addDate(myDate.substring(1, myDate.length - 1), 1));
								} else {
									tempObj.bc = el.BcType;
									tempObj.wrkhour1 = Number(wrkhr);
									tempObj.wrkhour2 = Number((hrs_ye - wrkhr).toFixed(2));
									tempObj.wrkhour3 = Math.round(hrs_ye * 100) / 100;
									bc = bc + 1;
									hrs_ye = hrs_ye - wrkhr;
								}
							}
							if (bc + 1 == w_shift[0].Work_Type) {
								tempObj.bc = Effective_Time_Arr[0].BcType;
								tempObj.wrkhour1 = Number(wrkhr);
								tempObj.wrkhour2 = Number((wrkhr - hrs_ye).toFixed(2));
								tempObj.wrkhour3 = Math.round(hrs_ye * 100) / 100;
								TempListWrkHour.push(tempObj);
								bc = 0;
								hrs_ye = 0;
								el = Effective_Time_Arr[bc];
								myDate = JSON.stringify(addDate(myDate.substring(1, myDate.length - 1), 1));
							} else {
								tempObj.bc = el.BcType;
								tempObj.wrkhour1 = Number(wrkhr);
								tempObj.wrkhour2 = Number((wrkhr - hrs_ye).toFixed(2));
								tempObj.wrkhour3 = Math.round((tempObj.wrkhour3 + hrs_ye) * 100) / 100;
								bc = bc + 1;
								hrs_ye = 0;
								el = Effective_Time_Arr[bc];
							}
						} else {
							//tempObj.bc = el.BcType;
							tempObj.wrkhour1 = Number(wrkhr);
							tempObj.wrkhour2 = Number((wrkhr - hrs_ye).toFixed(2));
							tempObj.wrkhour3 = Math.round(hrs_ye * 100) / 100;
							if (tempObj.wrkhour2 < 0) {
								if (bc + 1 == w_shift[0].Work_Type) {
									tempObj.date = addDate(rows[0].date.replace(/\"/g, ""), 1);
									tempObj.bc = Effective_Time_Arr[0].BcType;
									tempObj.wrkhour1 = Number(wrkhr);
									tempObj.wrkhour2 = Number((wrkhr - Math.abs(tempObj.wrkhour2)).toFixed(2));
									tempObj.wrkhour3 = Math.round(Math.abs(tempObj.wrkhour2) * 100) / 100;
									bc = 0;
									hrs_ye = 0;
									el = Effective_Time_Arr[bc];
									myDate = JSON.stringify(addDate(myDate.substring(1, myDate.length - 1), 1));
								} else {
									tempObj.bc = Effective_Time_Arr[bc + 1].BcType;
									tempObj.wrkhour1 = Number(wrkhr);
									tempObj.wrkhour2 = Number((wrkhr - Math.abs(tempObj.wrkhour2)).toFixed(2));
									tempObj.wrkhour3 = Math.round((tempObj.wrkhour3 + Math.abs(rows[0].wrkhour2)) * 100) / 100;
									bc = bc + 1;
									hrs_ye = 0;
									el = Effective_Time_Arr[bc];
								}
							}
						}
						TempListWrkHour.push(tempObj);
						editSoucre(item, el.BcType, i);
					} else {
						if (hrs >= wrkhr) {
							rows[0].wrkhour2 = 0;
							rows[0].wrkhour3 = Math.round(wrkhr * 100) / 100;
							hrs_ye = hrs - wrkhr;
							while (hrs_ye >= wrkhr) {
								if (bc + 1 == w_shift[0].Work_Type) {
									tempObj.date = addDate(rows[0].date.replace(/\"/g, ""), 1);
									tempObj.bc = Effective_Time_Arr[0].BcType;
									tempObj.wrkhour1 = Number(wrkhr);
									tempObj.wrkhour2 = Number((hrs_ye - wrkhr).toFixed(2));
									tempObj.wrkhour3 = Math.round(hrs_ye * 100) / 100;
									TempListWrkHour.push(tempObj);
									bc = 0;
									hrs_ye = hrs_ye - wrkhr;
									editSoucre(item, el.BcType, i);
									myDate = JSON.stringify(addDate(myDate.substring(1, myDate.length - 1), 1));

								} else {
									rows = filterData(TempListWrkHour, { date: [myDate.replace(/\"/g, "")], bc: [el.BcType] });
									rows[0].bc = el.BcType;
									rows[0].wrkhour1 = Number(wrkhr);
									rows[0].wrkhour2 = Number((hrs_ye - wrkhr).toFixed(2));
									rows[0].wrkhour3 = Math.round(hrs_ye * 100) / 100;
									TempListWrkHour.push(tempObj);
									bc = bc + 1;
									hrs_ye = hrs_ye - wrkhr;
									editSoucre(item, el.BcType, i);
								}
							}
							if (bc + 1 == w_shift[0].Work_Type) {
								tempObj.date = addDate(rows[0].date.replace(/\"/g, ""), 1);
								tempObj.bc = Effective_Time_Arr[0].BcType;
								tempObj.wrkhour1 = Number(wrkhr);
								tempObj.wrkhour2 = Number((wrkhr - hrs_ye).toFixed(2));
								tempObj.wrkhour3 = Math.round(hrs_ye * 100) / 100;
								TempListWrkHour.push(tempObj);
								bc = 0;
								hrs_ye = 0;
								editSoucre(item, el.BcType, i);
								myDate = JSON.stringify(addDate(myDate.substring(1, myDate.length - 1), 1));

							} else {
								rows = filterData(TempListWrkHour, { date: [myDate.replace(/\"/g, "")], bc: [el.BcType] });

								rows[0].bc = el.BcType;
								rows[0].wrkhour1 = Number(wrkhr);
								rows[0].wrkhour2 = Number((wrkhr - hrs_ye).toFixed(2));
								rows[0].wrkhour3 = Math.round((rows[0].wrkhour3 + hrs_ye) * 100) / 100;
								bc = bc + 1;
								hrs_ye = 0;
								editSoucre(item, el.BcType, i);
							}
						} else {
							rows[0].bc = el.BcType;
							rows[0].wrkhour1 = Number(wrkhr);
							rows[0].wrkhour2 = Number((rows[0].wrkhour2 - hrs).toFixed(2));
							rows[0].wrkhour3 += Math.round(hrs * 100) / 100;
							if (rows[0].wrkhour2 > 0) {
								editSoucre(item, el.BcType, i);
							} else {
								if (bc + 1 == w_shift[0].Work_Type) {
									tempObj.date = addDate(rows[0].date.replace(/\"/g, ""), 1);
									tempObj.bc = Effective_Time_Arr[0].BcType;
									tempObj.wrkhour1 = Number(wrkhr);
									tempObj.wrkhour2 = Number((wrkhr - Math.abs(rows[0].wrkhour2)).toFixed(2));
									tempObj.wrkhour3 = Math.round(Math.abs(rows[0].wrkhour2) * 100) / 100;
									TempListWrkHour.push(tempObj);
									bc = 0;
									hrs_ye = 0;
									editSoucre(item, el.BcType, i);
									myDate = JSON.stringify(addDate(myDate.substring(1, myDate.length - 1), 1));
								} else {
									rows = filterData(TempListWrkHour, { date: [myDate.replace(/\"/g, "")], bc: [el.BcType] });
									tempObj.date = rows[0].date.replace(/\"/g, "");
									tempObj.bc = Effective_Time_Arr[bc + 1].BcType;
									tempObj.wrkhour1 = Number(wrkhr);
									tempObj.wrkhour2 = Number((wrkhr - Math.abs(rows[0].wrkhour2)).toFixed(2));
									tempObj.wrkhour3 = Math.round((rows[0].wrkhour3 + Math.abs(rows[0].wrkhour2)) * 100) / 100;
									bc = bc + 1;
									hrs_ye = 0;
									TempListWrkHour.push(tempObj);
									editSoucre(item, el.BcType, i);
								}
							}
						}
					}
				}
			}
		});
		TempListWrkHour = [];
		return source;
	}
	/**
	 * 根据lockStore中的数据锁定工单
	 **/
	function LockGcd(source) {
		let temp = [];
		foreach(lockStore.getData().items, function (el) {
			let item = el.data;
			if (item.Resource_ID == "" || item.Date == "" || item.Scheduling == "") {
				let row = item.id;
				var j = row.substring(row.indexOf('-') + 1, row.length);
				Alert('提示：', "第" + j + "行有空数据");
				return false;
			} else {
				let filter = {
					Resource_ID: [item.Resource_ID],
					Date: [item.Date],
					Scheduling: [item.Scheduling],
				}
				let _row = filterData(temp, filter);
				if (_row.length > 0) {
					Alert('提示：', "不能有重复数据");
					return false;
				} else {
					temp.push({
						Resource_ID: item.Resource_ID,
						Date: item.Date,
						Scheduling: item.Scheduling,
					});
					foreach(source, function (el) {
						var d = new Date(el.Date).format('yyyy/MM/dd');
						if (el.Resource_ID == item.Resource_ID && d == item.Date.format('yyyy/MM/dd') && el.Scheduling == item.Scheduling) {
							el.Lock = item.Lock;
						}
					});
				}
			}
		});
		theGrid.collectionView.refresh();
	}
	var id = "cuscomp-" + randNumber();
	var data = [], TblEquWash_ary = [];
	var ResourceIndex = [], Work_Shift, BS_Work_Shift_Effective_Time,
		LocaltblItem, AllSettings, TblEquWashTime, WorkShopLine, Gcd_List;
	/*
	* @FactoryCalendar    加载工厂日历数据
	* @Work_Shift   加载班制表数据
	* @BS_Work_Shift_Effective_Time  加载班制明细表数据
	* @LocaltblItem  加载班次数据
	* @AllSettings  加载全览表数据
	* @TblEquWashTime 加载洗机工单数据
	* @WorkShopLine 加载车间档案数据
	* @Gcd_List  加载工单列表数据
	*/
	function sourceData() {
		Work_Shift = getListWithMultParams("Work_Shift", { Work_Noid: '' });
		BS_Work_Shift_Effective_Time = getListWithMultParams("BS_Work_Shift_Effective_Time", { Work_Noid: '' });
		LocaltblItem = getListWithMultParams("LocaltblItem", { Ftype: 'Work_Classes' });
		AllSettings = getListWithMultParams("Inventory", {});
		//TblEquWashTime = getListWithMultParams("TblEquWashTime", {});
		WorkShopLine = getListWithMultParams("WorkShopLine", { WorkShopId: '' });
		//Gcd_List = getListWithMultParams("Material_Issue_Plan", { Type: 1, Closed: 0 });
	}
	sourceData();

	/**
	 * 统计产线天数
	 * */
	function getResDayCount() {
		var day_ary = [], day_cout = [], count = 0;
		var source = theGrid.collectionView.sourceCollection;
		foreach(source, function (item) {
			if (day_ary[item.Date] == null) {
				day_ary[item.Date] = item.PlanQty;
				count++;
				day_cout[item.Resource] = count;
			} else {
				day_ary[item.Date] += item.PlanQty;
			}
		});
		return day_cout;
	}
	/**
	 * 删除洗机工单
	 * 
	 */
	function DelEquWash_GD() {
		let source = theGrid.collectionView.sourceCollection;
		for (let i = 0; i < source.length; i++) {
			if (source[i] != undefined) {
				if (source[i].GcdType == 3) {
					theGrid.itemsSource.remove(source[i]);
				}
			}
		}
		theGrid.collectionView.refresh();
	}
	var theGrid;
    
    
	/**
	 * 字段加载下拉数据
	 **/
	function CreateDataMap(ary, column) {
		let ActionsMap = getTop().newObject("wijmo.grid.DataMap", [ary, "id", "name"]);
		theGrid.columns.getColumn(column).dataMap = ActionsMap;
	}

	Ext.onReady(function () {
		var comp = Ext.get(id);
		var dom = comp.el.dom;
		var groupcolmn = getTop().newObject("wijmo.collections.CollectionView", [data, {
			groupDescriptions: ['ParentID', 'Resource'],
			sortDescriptions: ['Date', 'Resource_index', 'Scheduling', 'index']
		}]);
		//创建flexgrid表格对象
		theGrid = new getTop().newObject("wijmo.grid.FlexGrid", [dom, {
			showSort: true,
			allowSorting: false,
			autoGenerateColumns: false,
			headersVisibility: 'Column',
			selectionMode: 'Row',
			frozenColumns: 6,
			columns: [
				{ binding: 'index', header: '序号', minWidth: 80, allowSorting: false },
				{ binding: 'ParentID', header: '车间', width: 130, isReadOnly: true, visible: false, allowDragging: false },
				{ binding: 'Resource_ID', header: '设备', width: 130, visible: false, allowDragging: false },
				{ binding: 'Resource_index', header: '设备序号', width: 130, visible: false, allowDragging: false },
				{ binding: 'Resource', header: '设备', width: 130 },
				{ binding: 'Date', header: '日期', width: 90, dataType: 'Date', format: 'd', allowDragging: false, visible: true, allowSorting: false },
				{ binding: 'ScheduleStartDate', header: 't排开', width: 83, dataType: 'Date', format: 'd', isReadOnly: false, format: 'd', allowSorting: false, allowDragging: false },
				{ binding: 'ScheduleEndDate', header: 't排完', width: 79, isReadOnly: true, dataType: 'Date', format: 'd', allowSorting: false, allowDragging: false },
				{ binding: 'GcdType', header: '工单类型', isReadOnly: true, width: 5, visible: true, allowSorting: false, allowDragging: false },
				{ binding: 'PlanDateStart', header: 't计开', width: 83, dataType: 'Date', format: 'd', isReadOnly: true, format: 'd', visible: true, allowSorting: false, allowDragging: false },
				{ binding: 'ScheduleDateDifference', header: 'ΔT计排', width: 75, isReadOnly: true, format: 'd', allowSorting: false, allowDragging: false },
				{ binding: 'Scheduling', header: '班次', width: 80 },
				{ binding: 'SaOrderKey', header: '急', width: 60 },
				{ binding: 'CustomerKey', header: 'V', width: 50, isReadOnly: true, allowSorting: false, allowDragging: false },
				{ binding: 'Matching_icon', header: '齐', width: 30, isReadOnly: true, allowSorting: false, allowDragging: false },
				{ binding: 'Matching', header: '齐', width: 30, isReadOnly: true, visible: false, allowSorting: false, allowDragging: false },
				{ binding: 'Lock', header: '锁定', width: 80 },
				{ binding: 'Number', header: '工单', width: 106, isReadOnly: false, allowSorting: false, allowDragging: false },
				{ binding: 'FStatus', header: '工单状态', width: 65, visible: false, isReadOnly: true, allowSorting: false, allowDragging: false },
				{ binding: 'Inventory_ID', header: '物料编码', width: 110, isReadOnly: false, allowSorting: false, allowDragging: false },
				{ binding: 'Description', header: '物料名称', width: 180, isReadOnly: true, allowSorting: false, allowDragging: false },
				{ binding: 'BatchNO', header: '批次号', width: 73, isReadOnly: false, allowSorting: false, allowDragging: false },
				{ binding: 'PlanNpkg', header: '目标数量', width: 100, dataType: 'Number', isReadOnly: true, allowSorting: false, allowDragging: false },
				{ binding: 'StdInventory_ID', header: '半成品编码', width: 110, isReadOnly: false, visible: true, allowSorting: false, allowDragging: false },
				{ binding: 'MfgCatID', header: '砂型', width: 110, isReadOnly: true, visible: false,allowDragging: false },
				{ binding: 'SandTypeId', header: '砂型编码', width: 110, visible: false, visible: false,isReadOnly: true, allowDragging: false },
				{ binding: 'Unit_Weight', header: '规格', width: 45, isReadOnly: true, allowSorting: false, allowDragging: false },
				{ binding: 'PlanQty', header: '计划产量', width: 71, dataType: 'Number', aggregate: 'Sum', isReadOnly: true, allowSorting: false, allowDragging: false },
				{ binding: 'PlanDate', header: '∑T排', width: 53, dataType: 'Number', aggregate: 'Sum', isReadOnly: true, allowSorting: false, allowDragging: false },
				{ binding: '日占有率', header: '日占有率', width: 69, isReadOnly: true, dataType: 'Number', aggregate: 'Sum', allowSorting: false, allowDragging: false },
				{ binding: 'Summary', header: '备注', width: 110, isReadOnly: true, allowSorting: false, allowDragging: false },
				{ binding: 'HCapacity', header: '小时产能', width: 71, isReadOnly: true, dataType: 'Number', allowSorting: false, allowDragging: false },
				{ binding: '批占有率', header: '批占有率', width: 69, isReadOnly: true, dataType: 'Number', allowSorting: false, allowDragging: false },
				{ binding: 'PlanDate', header: 'T计', width: 60, dataType: 'Number', isReadOnly: true, visible: true, allowSorting: false, allowDragging: false },
				{ binding: 'PlanDateEnd', header: 't计完', width: 83, dataType: 'Date', format: 'd', isReadOnly: true, format: 'd', visible: true, allowSorting: false, allowDragging: false },
				{ binding: '日产能 ', header: '日产能', width: 110, isReadOnly: true, allowSorting: false, allowDragging: false },
				{ binding: 'OnePlanMAX', header: '批产能', width: 110, isReadOnly: true, allowSorting: false, allowDragging: false },
				{ binding: '实际日占有率', header: '实际日占有率', width: 110, isReadOnly: true, allowSorting: false, allowDragging: false },
				{ binding: '实际批占有率', header: '实际批占有率', width: 110, isReadOnly: true, allowSorting: false, allowDragging: false },
				{ binding: 'ActDateStart ', header: 't实开', width: 110, isReadOnly: true, allowSorting: false, allowDragging: false },
				{ binding: 'ActDateEnd', header: 't实完', width: 110, isReadOnly: true, allowSorting: false, allowDragging: false },
				{ binding: 'ActDate', header: 'T实', width: 110, isReadOnly: true, allowSorting: false, allowDragging: false },
				{ binding: 'T计实差', header: 'ΔT计实', width: 65, isReadOnly: true, allowSorting: false, allowDragging: false },
				{ binding: 'T排实', header: 'ΔT排实', width: 65, isReadOnly: true, format: 'd', allowSorting: false, allowDragging: false },
				{ binding: '物料分类', header: '物料分类', isReadOnly: true, width: 90, allowSorting: false, allowDragging: false },
				{ binding: 'apsno', header: '流水号', isReadOnly: true, width: 90, allowSorting: false, allowDragging: false },
			],
			beginningEdit: function (s, e) {
				var item = s.rows[e.row].dataItem;
				if (item.GcdType == 4) {
					e.cancel = true;
				}
			},
			itemsSource: groupcolmn,
			cellEditEnding: function (s, e) {
				var col = s.columns[e.col];
				if (col.binding == 'Date') {
					if (s.activeEditor.value != theGrid.getCellData(e.row, e.col)) {
						theGrid.setCellData(e.row, "ScheduleStartDate", s.activeEditor.value);
						theGrid.setCellData(e.row, "ScheduleEndDate", s.activeEditor.value);
					}
				}
				if (col.binding == 'Resource') {
					if (s.activeEditor.value != theGrid.getCellData(e.row, e.col)) {
						theGrid.setCellData(e.row, "Resource_ID", s.activeEditor.value);
					}
				}
			},
			refreshed: function () {
				let source = theGrid.itemsSource.items;
				let ary = [];
				let count = 0;
                let GdActionsMap = getTop().newObject("wijmo.grid.DataMap", [[], "id", "name"]);
                
                                    
				for (let i = 0; i < source.length; i++) {
					source[i].index = i;
                    GdActionsMap.collectionView.items.push({id:source[i].Number,name:source[i].Number+'/'+source[i].Description});
					if (ary[source[i].Resource] == null) {
						ary[source[i].Resource] = count;
						count++;
					}
					ResourceIndex.sort(function (a, b) { return a.Index - b.Index });
					foreach(ResourceIndex, function (el) {
						if (el.Resource_ID == source[i].Resource_ID) {
							source[i].Resource_index = el.Index;
						}
					});
				}
                theGrid.columns.getColumn("Number").dataMap =GdActionsMap 
			},
			updatedView: function () {
				btnMoveUpward.enable();
				btnMoveDown.enable();
			}
		}]);
		//启用列筛选过滤功能
		var filter = new getTop().newObject("wijmo.grid.filter.FlexGridFilter", [theGrid]);
		filter.defaultFilterType = getTop().wijmo.grid.filter.FilterType.Condition;
		filter.showSortButtons = false;
		//设置分组收缩级别
		theGrid.collapseGroupsToLevel(2);
		//启用wijmo表的列排序功能
		theGrid.sortingColumn.addHandler(function (s, e) {
			var view = s.collectionView, sds = view.sortDescriptions;
			e.cancel = true;
			if (e.data.ctrlKey) {
				sds.clear();
				return;
			}
			var prop = s.columns[e.col].binding, index = -1;
			for (var i = 0; i < sds.length && index < 0; i++) {
				if (sds[i].property == prop) {
					index = i;
				}
			}
			if (index < 0) { // not found, add now
				var sd = new getTop().wijmo.collections.SortDescription(prop, true);
				sds.push(sd);
			}
			else { // found, flip its direction
				var sd = new getTop().wijmo.collections.SortDescription(prop, !sds[index].ascending);
				sds.splice(index, 1, sd);
			}
		});
		//格式化wijmo表格列数据
		theGrid.formatItem.addHandler(function (s, e) {
			if (e.panel == s.cells) {
				var col = s.columns[e.col];
				var group_level = e._p.rows[e.row].level;

				if (group_level == 1) {
					var curFlexGridRow = theGrid.rows[e.row];
					curFlexGridRow.cssClass = 'cell-resource';
				}
				if (col.binding == 'GcdType') {
					if (group_level == undefined) {
						var GcdType = s.getCellData(e.row, theGrid.getColumn("GcdType").index);
						if (GcdType == 2) {
							var curFlexGridRow = theGrid.rows[e.row];
							curFlexGridRow.cssClass = 'cell-country';
						}
					}
				}
				if (col.binding == 'PlanDate') {
					var PlanDate = s.getCellData(e.row, theGrid.getColumn("PlanDate").index);
					var html = '<div style="color:{cls}"><span style="font-size:100%">{val}</span> ';
					html = html.replace('{val}', PlanDate == undefined ? 0 : PlanDate.toFixed(2));
					if (group_level == 2) {
						if (PlanDate > 11) {
							html = html.replace('{cls}', 'red');
						}
						e.cell.innerHTML = html;
					}
					if (group_level == 1) {
						if (PlanDate > 22) {
							html = html.replace('{cls}', '');
						}
						e.cell.innerHTML = html;
					}
					if (group_level == 0) {
						if (PlanDate > 22) {
							html = html.replace('{cls}', '');
						}
						e.cell.innerHTML = html;
					}
				}
				if (col.binding == 'PlanQty') {
					var diff = s.getCellData(e.row, theGrid.getColumn("PlanQty").index);
					var Resource_ID;
					var day_vount = getResDayCount()[e._p.rows[e.row].dataItem.name];
					if (group_level == 1 || group_level == 2) {
						Resource_ID = e._p.rows[e.row].dataItem.items[0].Resource_ID;
					}
					if (group_level == 3) {
						Resource_ID = e._p.rows[e.row].dataItem.items[0].Resource_ID;
					}
					var daycn = WorkShopLine.filter(function (p) {
						if (p.WorkShopId == Resource_ID) {
							return p;
						}
					});
					var cxn = daycn.length == 0 ? 0.001 : daycn[0].DayProductionCapacity;
					var html = '<div style="color:{cls}"><span style="font-size:100%">{val}</span> ';
					html = html.replace('{val}', diff == undefined ? 0 : diff.toFixed(2));
					if (group_level == 3) {
						if (diff > (cxn / 2)) {
							html = html.replace('{cls}', 'red');
						}
						e.cell.innerHTML = html;
					}
					if (group_level == 2) {
						if (diff > cxn) {
							html = html.replace('{cls}', 'red');
						}
						e.cell.innerHTML = html;
					}
					if (group_level == 1) {
						if (diff > (cxn * day_vount)) {
							html = html.replace('{cls}', 'red');
						}
						e.cell.innerHTML = html;
					}
					if (group_level == 0) {
						if (diff > (cxn * day_vount)) {
							html = html.replace('{cls}', 'red');
						}
						e.cell.innerHTML = html;
					}
				}
				if (col.binding == 'Matching_icon') {
					var matching = s.getCellData(e.row, theGrid.getColumn("Matching").index);
					var html = '<div style="color:{cls}"><span style="font-size:100%">&nbsp<i class="wj-glyph-{glyph}"></i></span> ';
					if (matching == 1) {
						html = html.replace('{cls}', 'green');
						html = html.replace('{glyph}', 'circle');
						e.cell.innerHTML = html;
					}
					if (matching == 0) {
						html = html.replace('{cls}', 'red');
						html = html.replace('{glyph}', 'circle');
						e.cell.innerHTML = html;
					}
				}
				if (col.binding == 'SaOrderKey') {
					var saOrderKey = s.getCellData(e.row, theGrid.getColumn("SaOrderKey").index);
					var html = '<input type="text" style="color:{cls};border:0;" value="{val}" /> ';
					if (saOrderKey == 8) {
						html = html.replace('{cls}', 'red');
						html = html.replace('{val}', '急');
					}
					if (saOrderKey == 0) {
						html = html.replace('{cls}', 'greed');
						html = html.replace('{val}', '');
					}
				}
				if (col.binding == '日占有率') {
					var temp = s.getCellData(e.row, theGrid.getColumn("PlanQty").index);
					var day_vount = getResDayCount()[e._p.rows[e.row].dataItem.name];
					var Resource_ID;
					if (group_level == 1 || group_level == 2) {
						Resource_ID = e._p.rows[e.row].dataItem.items[0].Resource_ID;
					}
					var daycn = WorkShopLine.filter(function (p) {
						if (p.WorkShopId == Resource_ID) {
							return p;
						}
					});
					var cxn = daycn.length == 0 ? 0.001 : daycn[0].DayProductionCapacity;
					var html = '<div style="color:{cls}"><span style="font-size:100%">{val}%</span> ';
					if (group_level == 0) {
						html = html.replace('{val}', '');
					} else if (group_level == 1) {
						html = html.replace('{val}', parseInt(((temp) / cxn) * 100 / day_vount));
					} else if (group_level == 2) {
						html = html.replace('{val}', parseInt(((temp) / cxn) * 100));
					} else {
						html = html.replace('{val}', '');
					}
					e.cell.innerHTML = html;
				}
				if (col.binding == '批占有率') {
					var html = '<div style="color:{cls}"><span style="font-size:100%">{val}%</span> ';
					if (group_level == 0) {
						html = html.replace('{val}', '');
					} else if (group_level == 1) {
						html = html.replace('{val}', '');
					} else if (group_level == 2) {
						html = html.replace('{val}', '');
					} else if (group_level == 3) {
						html = html.replace('{val}', '');
					} else {
						var temp = s.getCellData(e.row, theGrid.getColumn("PlanQty").index);
						var invid = s.getCellData(e.row, theGrid.getColumn("Inventory_ID").index);
						var WipId = s.getCellData(e.row, theGrid.getColumn("ParentID").index);
						var allsettings = AllSettings.filter(function (p) {
							if (p.Inventory_ID == invid && p.WipID == WipId) {
								return p;
							}
						});
						var OnePlanMAX = allsettings.length > 0 ? allsettings[0].OnePlanMAX : 1;
						html = html.replace('{val}', parseInt((temp / OnePlanMAX) * 100));
					}
					e.cell.innerHTML = html;
				}
				if (col.binding == 'ScheduleDateDifference') {
					var start = s.getCellData(e.row, theGrid.getColumn("PlanDateStart").index);
					var temp2 = s.getCellData(e.row, theGrid.getColumn("ScheduleEndDate").index);
					var html = '<div style="color:{cls}"><span style="font-size:100%">{val}</span> ';
					html = html.replace('{val}', Math.round((new Date(start) - new Date(temp2)) / 1000 / 60 / 60 / 24));
					e.cell.innerHTML = html;
				}
			}
		});
		//添加是否急单列下拉数据
		CreateDataMap([{ id: 8, name: '急' }, { id: 0, name: '否' }], "SaOrderKey");
		//添加班制列下拉数据
		let Scheduling_Map = [];
		foreach(LocaltblItem, function (el) {
			Scheduling_Map.push({ id: el.FCode, name: el.FDescript });
		});
		CreateDataMap(Scheduling_Map, "Scheduling");
		//添加是否锁定下拉数据
		CreateDataMap([{ id: 1, name: '已锁' }, { id: 0, name: '未锁' }], "Lock");
	});
	/**
	 * 读取原计划
	 * 读取当天以前的排产计划到当前排产界面
	 * */
	let btnReadOldPlan = Ext.create('Ext.Button', {
		tooltip: '读取原计划',
		glyph: 0xf5ae,
		handler: function () {
			var source = theGrid.collectionView.sourceCollection;
			getTopWindow().openWindow("原排产计划", "/ProductionPlanGcd?disble_operate_type=Add,Edit,Delete,Print,Record,BackRecord,Verify,Search&selectmode=true&Maker=" + getTopWindow().username + "&MakeDate<" + now, 900, 600, function (v) {
				if (v != null && typeof (v) == "object") {
					if (v.length == 2) {
						source.splice(0, source.length);
						theGrid.collectionView.refresh();
						var child_list = getListWithMultParams("ProductionPlanGcdDetail", { ProductionNo: v[1].ProductionNo });
						child_list.sort(function (a, b) { return a.Noid - b.Noid });
						let pid = child_list[0].WIP_ID;
						let ary1 = [];
						foreach(WorkShopLine, function (el) {
							if (el.Parent_ID == pid) {
								let obj = new Object();
								obj.id = el.Description;
								obj.name = el.Description;
								ary1.push(obj);
							}
						});
						CreateDataMap(ary1, "Resource");
						Gcd_List = [];
						Gcd_List = getListWithMultParams("Material_Issue_Plan_NFSAP", { Des_StockID: pid, Type: 1, Closed: 0 });
						foreach(child_list, function (item) {
							let nowDate = new Date().format('yyyy/MM/dd');
							let gcd_temp = Gcd_List.filter(function (p) {
								if (p.NO == item.IssuleNo) {
									return p;
								}
							});
							if (item.IssuleNo == null || item.IssuleNo == "") {
								gcd_temp.length = 2;
							}
							if (gcd_temp.length > 0 || items.IssuleNo.indexOf('XGCD') == 0) {
								let ScheduleEndDate = new Date(item.ScheduleEndDate).format('yyyy/MM/dd');
								if (ScheduleEndDate >= nowDate) {
									var temp = WorkShopLine.filter(function (p) {
										if (item.Resource_ID == p.WorkShopId) {
											return p;
										}
									});
									var temp_allsetting = AllSettings.filter(function (p) {
										if (item.Inventory_id == p.Inventory_ID && p.WipID == pid) {
											return p;
										}
									});
									var view = theGrid.collectionView;
									var newItem = view.addNew();

									newItem.Resource_ID = item.Resource_ID;
									newItem.Resource_index = item.Resource_index;
									newItem.Resource = temp.length > 0 ? temp[0].Description : '';
									newItem.ParentID = item.WIP_ID;
									newItem.Date = getTop().wijmo.Globalize.parseDate(item.ScheduleEndDate, 'yyyy/MM/dd');
									switch (item.Scheduling) {
										case "白班":
											newItem.Scheduling = '001';
											break;
										case "夜班":
											newItem.Scheduling = '002';
											break;
										case "早班":
											newItem.Scheduling = '003';
											break;
										case "晚班":
											newItem.Scheduling = '004';
											break;
										default: newItem.Scheduling = item.Scheduling;
									}
									newItem.Inventory_ID = item.Inventory_id;
									newItem.Lock = 0;
									newItem.Description = temp_allsetting.length > 0 ? temp_allsetting[0].Description : '';
									newItem.Number = item.IssuleNo;
									newItem.BatchNO = item.BatchNO;
									newItem.PlanQty = item.IssueQty;
									newItem.PlanDateStart = getTop().wijmo.Globalize.parseDate(item.PbeginDate, 'yyyy/MM/dd');
									newItem.PlanDateEnd = getTop().wijmo.Globalize.parseDate(item.PEndDate, 'yyyy/MM/dd');
									newItem.ScheduleStartDate = getTop().wijmo.Globalize.parseDate(item.ScheduleStartDate, 'yyyy/MM/dd');
									newItem.ScheduleEndDate = getTop().wijmo.Globalize.parseDate(item.ScheduleEndDate, 'yyyy/MM/dd');
									newItem.PlanDate = item.MfgPlanTime;
									newItem.PlanNpkg = item.PlanNpkg;
									newItem.StdInventory_ID = item.StdInventory_ID;
									newItem.MfgCatID = item.MfgCatID;
									newItem.SandTypeId = temp_allsetting.length > 0 ? temp_allsetting[0].SandTypeId : '';
									newItem.HCapacity = item.HCapacity;
									newItem.Summary = item.Summary;
									newItem.Matching = item.Matching;
									newItem.SaOrderKey = item.SaOrderKey;
									newItem.ScheduleDateDifference = 0;
									newItem.GcdType = 0;
									newItem.FStatus = '';
									newItem.Capacity = temp_allsetting.length > 0 ? temp_allsetting[0].Capacity : '';
									newItem.OnePlanMAX = temp_allsetting.length > 0 ? temp_allsetting[0].OnePlanMAX : '';
									newItem.Unit_Weight = temp_allsetting.length > 0 ? temp_allsetting[0].Style : 1;
									view.commitNew();
								}
							}
						});
					} else {
						Alert('提示:', '只能选择一条数据！');
					}
				}
			});
		}
	});
	/**
	 * 读当天计划
	 * 读取当前的排产计划到当前的排产界面
	 * */
	let btnReadNowPlan = Ext.create('Ext.Button', {
		tooltip: '读当天计划',
		glyph: 0xf0ce,
		handler: function () {
			var source = theGrid.collectionView.sourceCollection;
			getTopWindow().openWindow("当天排产计划", "/ProductionPlanGcd?disble_operate_type=Add,Edit,Delete,Print,Record,BackRecord,Verify,Search&selectmode=true&Maker=" + getTopWindow().username + "&MakeDate=" + Common.formatDate(now, 'yyyy/MM/dd'), 900, 600, function (v) {
				if (v != null && typeof (v) == "object") {
					if (v.length == 2) {
						source.splice(0, source.length);
						theGrid.collectionView.refresh();
						var child_list = getListWithMultParams("ProductionPlanGcdDetail", { ProductionNo: v[1].ProductionNo });
						child_list.sort(function (a, b) { return a.Noid - b.Noid });
						let pid = child_list[0].WIP_ID;
						let ary1 = [];
						foreach(WorkShopLine, function (el) {
							if (el.Parent_ID == pid) {
								let obj = new Object();
								obj.id = el.Description;
								obj.name = el.Description;
								ary1.push(obj);
							}
						});
						CreateDataMap(ary1, "Resource");
						Gcd_List = [];
						Gcd_List = getListWithMultParams("Material_Issue_Plan_NFSAP", { Des_StockID: pid, Type: 1, Closed: 0 });
						foreach(child_list, function (item) {
							let gcd_temp = Gcd_List.filter(function (p) {
								if (p.NO == item.IssuleNo) {
									return p;
								}
							});
							if (item.IssuleNo == null || item.IssuleNo == "") {
								gcd_temp.length = 2;
							}
							if (gcd_temp.length > 0 || items.IssuleNo.indexOf('XGCD') == 0) {
								var temp = WorkShopLine.filter(function (p) {
									if (item.Resource_ID == p.WorkShopId) {
										return p;
									}
								});
								var temp_allsetting = AllSettings.filter(function (p) {
									if (item.Inventory_id == p.Inventory_ID && p.WipID == pid) {
										return p;
									}
								});
								var view = theGrid.collectionView;
								var newItem = view.addNew();
								newItem.Resource_index = item.Resource_index;
								newItem.Resource_ID = item.Resource_ID;
								newItem.Resource = temp.length > 0 ? temp[0].Description : '';
								newItem.ParentID = item.WIP_ID;
								newItem.Date = getTop().wijmo.Globalize.parseDate(item.ScheduleEndDate, 'yyyy/MM/dd');
								switch (item.Scheduling) {
									case "白班":
										newItem.Scheduling = '001';
										break;
									case "夜班":
										newItem.Scheduling = '002';
										break;
									case "早班":
										newItem.Scheduling = '003';
										break;
									case "晚班":
										newItem.Scheduling = '004';
										break;
									default: newItem.Scheduling = item.Scheduling;
								}
								newItem.Inventory_ID = item.Inventory_id;
								newItem.Lock = 0;
								newItem.Description = temp_allsetting.length > 0 ? temp_allsetting[0].Description : '';
								newItem.Number = item.IssuleNo;
								newItem.BatchNO = item.BatchNO;
								newItem.PlanQty = item.IssueQty;
								newItem.PlanDateStart = getTop().wijmo.Globalize.parseDate(item.PbeginDate, 'yyyy/MM/dd');
								newItem.PlanDateEnd = getTop().wijmo.Globalize.parseDate(item.PEndDate, 'yyyy/MM/dd');
								newItem.ScheduleStartDate = getTop().wijmo.Globalize.parseDate(item.ScheduleStartDate, 'yyyy/MM/dd');
								newItem.ScheduleEndDate = getTop().wijmo.Globalize.parseDate(item.ScheduleEndDate, 'yyyy/MM/dd');
								newItem.PlanDate = item.MfgPlanTime;
								newItem.PlanNpkg = item.PlanNpkg;
								newItem.StdInventory_ID = item.StdInventory_ID;
								newItem.MfgCatID = item.MfgCatID;
								newItem.SandTypeId = temp_allsetting.length > 0 ? temp_allsetting[0].SandTypeId : '';
								newItem.HCapacity = item.HCapacity;
								newItem.Summary = item.Summary;
								newItem.Matching = item.Matching;
								newItem.SaOrderKey = item.SaOrderKey;
								newItem.GcdType = 0;
								newItem.FStatus = '';
								newItem.Capacity = temp_allsetting.length > 0 ? temp_allsetting[0].Capacity : '';
								newItem.OnePlanMAX = temp_allsetting.length > 0 ? temp_allsetting[0].OnePlanMAX : '';
								newItem.Unit_Weight = temp_allsetting.length > 0 ? temp_allsetting[0].Style : 1;
								view.commitNew();
							}
						});
					} else {
						Alert('提示:', '只能选择一条数据！');
					}
				}
			});
		}
	});
	/**
	 * 未清生产订单
	 * 从工程单表中读取有效订单，压单的记录行背景色标记红色，将选择的工单写入到排产界面
	 **/
	let btnNotFinishProductionOrder = Ext.create('Ext.Button', {
		tooltip: '未清生产订单',
		glyph: 0xf4ce,
		handler: function () {
			var rows = theGrid.selectedItems[0];
			var source = theGrid.collectionView.sourceCollection;
			var gd_arry = [];
			var cond = {
				t: "and", child: []
			}
			foreach(source, function (item) {
				if (rows.Resource_ID == item.Resource_ID) {
					gd_arry.push(item.Number);
				}
			});
			var oneTbar = new Ext.Toolbar({
				items: [{
					labelWidth: 30,
					xtype: 'textfield',
					name: 'WipId',
					fieldLabel: '车间',
					value: ''
				}, {
					labelWidth: 60,
					xtype: 'textfield',
					name: 'WipId',
					fieldLabel: '关键容器',
					value: ''
				}, {
					xtype: 'datefield',
					name: 'plan_start',
					fieldLabel: '计划工开时间起'
				}, {
					xtype: 'datefield',
					name: 'plan_end',
					fieldLabel: '计划工开时间止'
				}, {
					tooltip: '查询',
					glyph: 0xf002,
					handler: function () {

					}
				}]
			});
			function wnd(list, rows) {
				foreach(list, function (el) {
					var inv = AllSettings.filter(function (p) {
						if (p.Inventory_ID == el.Inventory_ID && p.WipID == rows.ParentID) {
							return p;
						}
					});
					el.Description = inv.length == 0 ? "" : inv[0].Description;
				});
				var store = Ext.create('Ext.data.Store', {
					fields: ['Des_StockID', 'NO', 'BatchNO', 'JiHao', 'Inventory_ID', 'Description', 'CQty', 'WrkHrs', 'ReqDate', 'DuDate', 'CUST', 'Project', 'SelfMfg_OrdersPO', 'Date', 'IsProduceResIssuePlan'],
					sortable: true,
					sorters: [{ property: "ReqDate", direction: "ASC" }], //给定一个默认的排序方式      
					data: list
				});
				var grid = getTop().Ext.create('Ext.grid.Panel', {
					store: store,
					region: 'south',
					frame: false,
					width: 900,
					height: '100%',
					viewConfig: {
						columnLines: true,
						stripeRows: true,
						enableTextSelection: true,
						animateShadow: true,
						forceFit: true,
						getRowClass: function (record) {
							let nowDate = new Date().format('yyyy/MM/dd');
							let tmdate = new Date(record.data.DuDate).format('yyyy/MM/dd');;
							if (tmdate < nowDate) {
								return "bglightred";
							}
						}
					},
					selModel: {
						mode: 'MULTI',
						checkboxSelect: true,
						injectCheckbox: 1,
						type: 'checkboxmodel'
					},
					plugins: {
						gridfilters: true
					},
					columns: [
						{ header: '', xtype: 'rownumberer', width: 45, align: 'center', sortable: false, menuDisabled: true },
						{
							dataIndex: 'Des_StockID', header: '车间', width: 51, sortable: false, menuDisabled: false,
							filter: {
								type: 'string', itemDefaults: { emptyText: '查询...' }
							}
						},
						{ dataIndex: 'NO', header: '工程单号', width: 109, sortable: false, menuDisabled: true },
						{
							dataIndex: 'JiHao', text: '查询', header: '关键容器', width: 87, sortable: false, menuDisabled: false,
							filter: {
								type: 'string', itemDefaults: { emptyText: '查询...' }, value: rows.Resource_ID
							}
						},
						{ dataIndex: 'BatchNO', header: '批次号', width: 112, sortable: false, menuDisabled: true },
						{ dataIndex: 'LvWanAct', header: '半成品工单号', width: 112, sortable: false, menuDisabled: true },
						{ dataIndex: 'Inventory_ID', header: '成品', width: 112, sortable: false, menuDisabled: true },
						{ dataIndex: 'Description', header: '成品名称', width: 200, sortable: false, menuDisabled: true },
						{ dataIndex: 'CQty', header: '生产总量', width: 74, sortable: false, menuDisabled: true },
						{ dataIndex: 'WrkHrs', header: '总工时', width: 61, sortable: false, menuDisabled: true },
						{ dataIndex: 'ReqDate', header: '计划工开时间', width: 100, sortable: false, menuDisabled: true },
						{ dataIndex: 'DuDate', header: '要求完成时间', width: 100, sortable: false, menuDisabled: true },
						{ dataIndex: 'CUST', header: '客户编码', width: 74, sortable: false, menuDisabled: true },
						{ dataIndex: 'Project', header: '计划单号', width: 74, sortable: false, menuDisabled: true },
						{ dataIndex: 'SelfMfg_OrdersPO', header: '车间加工计划号', width: 100, sortable: false, menuDisabled: true },
						{ dataIndex: 'Date', header: '开单日期', width: 100, sortable: false, menuDisabled: true },
						{ dataIndex: 'IsProduceResIssuePlan', header: '排程状态', width: 100, sortable: false, menuDisabled: true },
					],
					tbar: {
						//items: [oneTbar]  
					},
				});
				var init_wind = getTop().Ext.create('Ext.window.Window', {
					title: '未清生产订单',
					width: 830,
					height: 480,
					modal: true,
					maximizable: true,
					items: [grid],
					listeners: {
						resize: function (wn, width, height) {
							let grid = wn.items.items[0];
							grid.setHeight(height - 80);
							grid.setWidth(width - 15);
							oneTbar.setSize(400, 100);
						}
					},
					fbar: [
						{
							type: 'button',
							text: '选择',
							handler: function () {
								let selectrows = grid.getSelectionModel().getSelection();
								if (selectrows.length > 0) {
                                    
									for (var i = 0; i < selectrows.length; i++) {
										var item = selectrows[i].data;

										var temp = AllSettings.filter(function (p) {
											if (item.Inventory_ID == p.Inventory_ID) {
												return p;
											}
										});
										var bcp_invid = '';
										var Style = temp.length > 0 ? temp[0].Style : 1;
										var CQty = (item.CQty * Style) / 1000;
										var view = theGrid.collectionView;
										var newItem = view.addNew();
										let nowDate = new Date().format('yyyy/MM/dd');
										if (new Date(item.DuDate) < new Date(nowDate)) {
											let temp_date = nowDate.format('yyyy/MM/dd');
											newItem.Date = getTop().wijmo.Globalize.parseDate(temp_date, 'yyyy/MM/dd');
											newItem.ScheduleEndDate = getTop().wijmo.Globalize.parseDate(temp_date, 'yyyy/MM/dd');
											newItem.ScheduleStartDate = getTop().wijmo.Globalize.parseDate(temp_date, 'yyyy/MM/dd');
										} else {
											newItem.Date = getTop().wijmo.Globalize.parseDate(item.DuDate, 'yyyy/MM/dd');
											newItem.ScheduleEndDate = getTop().wijmo.Globalize.parseDate(item.DuDate, 'yyyy/MM/dd');
											newItem.ScheduleStartDate = getTop().wijmo.Globalize.parseDate(item.DuDate, 'yyyy/MM/dd');
										}
										newItem.ParentID = rows.ParentID;
										newItem.FStatus = item.FStatus;
										newItem.Lock = 0;
										newItem.Capacity = item.Capacity;
										newItem.OnePlanMAX = temp.length > 0 ? temp[0].OnePlanMAX : '';
										newItem.Resource_ID = rows.Resource_ID;
										newItem.Resource_index = rows.Resource_index;
										newItem.Resource = rows.Resource;
										newItem.Scheduling = '';
										newItem.MfgCatID = temp.length > 0 ? temp[0].SandType : '';
										newItem.SandTypeId = temp.length > 0 ? temp[0].SandTypeId : '';
										newItem.Number = item.NO;
										newItem.BcpNumber = item.LvWanActl;
										newItem.Inventory_ID = item.Inventory_ID;
										newItem.Description = temp.length > 0 ? temp[0].Description : '';
										newItem.StdInventory_ID = bcp_invid;
										newItem.BatchNO = item.BatchNO;
										newItem.PlanQty = CQty;
										newItem.PlanNpkg = item.CQty;
										newItem.PlanDateStart = getTop().wijmo.Globalize.parseDate(item.ReqDate, 'yyyy/MM/dd');
										newItem.PlanDateEnd = getTop().wijmo.Globalize.parseDate(item.DuDate, 'yyyy/MM/dd');
										newItem.Matching = item.Matching;
										newItem.PlanDate = CQty / (temp.length > 0 ? temp[0].Capacity : 1);
										newItem.Unit_Weight = temp.length > 0 ? temp[0].Style : '';
										newItem.HCapacity = temp.length > 0 ? temp[0].Capacity : '';
										newItem.GcdType = 0;
										newItem.SaOrderKey = 0;
										view.commitNew();
                                        
									}
                                    
									theGrid.collectionView.refresh();
									init_wind.close();
									return true;
								} else {
									Alert('提示：', '请选择数据！');
									return false;
								}
							}
						}, {
							type: 'button',
							text: '取消',
							handler: function () {
								init_wind.close();
							}
						}
					]
				});
				init_wind.show();
			}
			let con_ary = [
				{ c: "Closed", cp: '=', v: 0 },
				{ c: "Des_StockID", cp: '=', v: rows.ParentID }
			];
			if(gd_arry.length > 0 ){
				con_ary.push({ c: "NO", cp: 'notin', v: gd_arry.join(";") })
			}
			cond.child = con_ary;
			Wait.Start(null, "正在执行操作，请稍候.....");
			list = getListWithMultParams("Material_Issue_Plan", { _cdt: jsonEncode(cond) },
				null, {
				callback: function (vitems) {
					Wait.hide();
					wnd(vitems, rows == undefined ? '' : rows);
					let pid = rows.ParentID;
					let ary1 = [];
					foreach(WorkShopLine, function (el) {
						if (el.Parent_ID == pid) {
							let obj = new Object();
							obj.id = el.Description;
							obj.name = el.Description;
							ary1.push(obj);
						}
					});
					CreateDataMap(ary1, "Resource");
				},
				async: function () {

				}
			});
		}
	});
	/**
	 * 齐套分析
	 * 排产界面中的工单与sap给的数据做对比，齐套标记绿色，不齐套标记红色
	*/
	let btnBundleAnalysis = Ext.create('Ext.Button', {
		tooltip: '齐套分析',
		glyph: 0xf058,
		handler: function () {
			let cv = theGrid.itemsSource;
			let Des_StockID = cv.currentItem.ParentID

			var gd_list = getListWithMultParams("Material_Issue_Plan_SAP", { Des_StockID: Des_StockID, Matching: 0 });
			var source = theGrid.collectionView.sourceCollection;
			foreach(source, function (item) {
				if (item.GcdType == 4) {
					return;
				}
				var temp = gd_list.filter(function (p) {
					if (p.NO == item.Number) {
						return p;
					}
				});
				if (temp.length > 0) {
					item.Matching = 0;
				} else {
					item.Matching = 1;
				}
			});
			theGrid.collectionView.refresh();
			Alert('提示：', '齐套分析完成');
		}
	});

	/**
	 * 查看指定工单缺料
	 * 根据选择的工去sap的接口查询缺少的物料
	 **/
	let btnViewGdItemShortage = Ext.create('Ext.Button', {
		tooltip: '查看指定工单缺料',
		glyph: 0xf689,
		handler: function () {
			var Garray = [];
			let cv = theGrid.itemsSource;
			if (cv.currentItem == null || cv.currentItem == '' || cv.currentItem == undefined) {
				Alert('提示：', '请选择需要查询的物料！');
				return false;
			} else {
				Garray.push({
					AUFNR: cv.currentItem.Number
				});
			}
			var arg = {
				//url: 'http://saperpqas.nipponpaint.com.cn:8000/sap/bc/srt/rfc/sap/zws_eccaps_03/510/zws_eccaps_03/zws_eccaps_03',
				url: 'http://sapr3pci01.nipponpaint.com.cn:8000/sap/bc/srt/rfc/sap/zws_eccaps_03/500/zws_eccaps_03/binding',
				username: 'APSLOGON',
				password: 'initinit',
				method: 'zws_eccaps_03',
				argument: {
					ET_PRODRET: jsonEncode([]),
					IT_AUFNR: jsonEncode(Garray),
					ET_SHORTMAT: jsonEncode([])
				},
			};
			Wait.Start(null, "数据同步中........");
			var ret = callWebService(arg, true, (ret) => {
				Wait.hide();
				if (!ret[0].success) {
					alert(ret[0].message);
					return;
				}

				var retobj = jsonDecode(ret[1]);
				var st_data = [];
				foreach(retobj.ET_SHORTMAT, function (ve) {
					st_data.push({
						AUFNR: ve.AUFNR,
						MATNR: ve.MATNR,
						MAKTX: ve.MAKTX,
						BDMNG: ve.BDMNG,
						QL_QTY: ve.QL_QTY,
						MEINS: ve.MEINS
					});
				});

				var store = Ext.create('Ext.data.Store', {
					fields: ['AUFNR', 'MATNR', 'MAKTX', 'BDMNG', 'QL_QTY', 'MEINS'],
					data: st_data
				});
				var grid = Ext.create('Ext.grid.Panel', {
					store: store,
					height: 400,
					stripeRows: true,
					viewConfig: { forceFit: true },
					columns: [
						{ header: '', xtype: 'rownumberer', width: 45, align: 'center', sortable: false, menuDisabled: true },
						{ header: 'SAP生产单号', dataIndex: 'AUFNR', width: 117, align: 'center', sortable: false, menuDisabled: true },
						{ header: '组件物料编码', dataIndex: 'MATNR', width: 100, align: 'center', sortable: false, menuDisabled: true },
						{ header: '组件描述', dataIndex: 'MAKTX', width: 330, align: 'center', sortable: false, menuDisabled: true },
						{ header: '组件数量', dataIndex: 'BDMNG', width: 73, align: 'center', sortable: false, menuDisabled: true },
						{ header: '缺料数量', dataIndex: 'QL_QTY', width: 73, align: 'center', sortable: false, menuDisabled: true },
						{ header: '单位', dataIndex: 'MEINS', width: 47, align: 'center', sortable: false, menuDisabled: true }
					]
				});
				var init_wind = Ext.create('Ext.window.Window', {
					title: cv.currentItem.Number + ':短缺物料',
					width: 830,
					height: 480,
					modal: true,
					items: [grid],
					listeners: {
						resize: function (wn, width, height, eOpts) {
							let grid = wn.items.items[0];
							grid.setHeight(height - 80);
							grid.setWidth(width - 15);
						}
					},
					fbar: [
						{
							type: 'button',
							text: '确定',
							handler: function () {
								init_wind.close();
							}
						}
					]
				});
				init_wind.show();
			});
		}
	});
	/**
	 * 工单缺料明细
	 * 将界面中的工单号传入sap的接口查询出工单的缺料明细
	*/
	let btnViewGdListShortage = Ext.create('Ext.Button', {
		tooltip: '工单缺料明细',
		glyph: 0xf03a,
		handler: function () {
			var Garray = [];
			var source = theGrid.collectionView.sourceCollection;
			foreach(source, function (item) {
				if (item.Matching == 0) {
					Garray.push({
						AUFNR: item.Number
					});
				}
			});
			Wait.Start(null, "数据同步中........");
			var arg = {
				//url: 'http://saperpqas.nipponpaint.com.cn:8000/sap/bc/srt/rfc/sap/zws_eccaps_03/510/zws_eccaps_03/zws_eccaps_03',
				url: 'http://sapr3pci01.nipponpaint.com.cn:8000/sap/bc/srt/rfc/sap/zws_eccaps_03/500/zws_eccaps_03/binding',
				username: 'APSLOGON',
				password: 'initinit',
				method: 'zws_eccaps_03',
				argument: {
					ET_PRODRET: jsonEncode([]),
					IT_AUFNR: jsonEncode(Garray),
					ET_SHORTMAT: jsonEncode([])
				},
			};
			var st_data = [];
			var ret = callWebService(arg, true, (ret) => {
				Wait.hide();
				if (!ret[0].success) {
					alert(ret[0].message);
					return;
				}
				var retobj = jsonDecode(ret[1]);

				foreach(retobj.ET_SHORTMAT, function (ve) {
					st_data.push({
						AUFNR: ve.AUFNR,
						MATNR: ve.MATNR,
						MAKTX: ve.MAKTX,
						BDMNG: ve.BDMNG,
						QL_QTY: ve.QL_QTY,
						MEINS: ve.MEINS
					});
				});
				var store = Ext.create('Ext.data.Store', {
					fields: ['AUFNR', 'MATNR', 'MAKTX', 'BDMNG', 'QL_QTY', 'MEINS'],
					data: st_data
				});
				var grid = Ext.create('Ext.grid.Panel', {
					store: store,
					height: 400,
					stripeRows: true,
					viewConfig: { forceFit: true },
					columns: [
						{ header: '', xtype: 'rownumberer', width: 45, align: 'center', sortable: false, menuDisabled: true },
						{ header: 'SAP生产单号', dataIndex: 'AUFNR', width: 117, align: 'center', sortable: false, menuDisabled: true },
						{ header: '组件物料编码', dataIndex: 'MATNR', width: 100, align: 'center', sortable: false, menuDisabled: true },
						{ header: '组件描述', dataIndex: 'MAKTX', width: 330, align: 'center', sortable: false, menuDisabled: true },
						{ header: '组件数量', dataIndex: 'BDMNG', width: 73, align: 'center', sortable: false, menuDisabled: true },
						{ header: '缺料数量', dataIndex: 'QL_QTY', width: 73, align: 'center', sortable: false, menuDisabled: true },
						{ header: '单位', dataIndex: 'MEINS', width: 47, align: 'center', sortable: false, menuDisabled: true }
					],
					tbar: [
						{
							text: '导出Excel',
							glyph: 0xf1c3,
							handler: function () {
								grid2Excel(grid, "工单缺料明细");
							}
						}
					]
				});
				var init_wind = Ext.create('Ext.window.Window', {
					title: '短缺物料',
					width: 830,   //Number型，也可以是字符串类型 
					height: 480,
					modal: true,
					maximizable: true,
					items: [grid],
					listeners: {
						resize: function (wn, width, height, eOpts) {
							let grid = wn.items.items[0];
							grid.setHeight(height - 80);
							grid.setWidth(width - 15);
						},
						show: function () {
							Wait.hide();
						}
					},
					fbar: [
						{
							type: 'button',
							text: '确定',
							handler: function () {
								init_wind.close();
							}
						}
					]
				});
				init_wind.show();
			});
		}
	});
	/**
	 * 砂型排序
	 * 将每一个班次内的工单按照砂型编码进行排序
	 * */
	let btnSandSorting = Ext.create('Ext.Button', {
		text: '砂',
		tooltip: '砂型排序',
		glyph: 0xf338,
        disabled:true,
		handler: function () {
			var res_ary;
			var cv = theGrid.collectionView.sourceCollection;
			res_ary = JsonArrayGroup(cv);
			var store = Ext.create('Ext.data.Store', {
				fields: ['value', 'text'],
				data: []
			});
			var store2 = Ext.create('Ext.data.Store', {
				fields: ['value', 'text'],
				data: []
			});
			foreach(res_ary, function (item) {
				store2.addSorted({
					value: item.Resource_ID,
					text: item.Resource
				});
			});
			var DateCbox = new Ext.form.field.Tag({
				xtype: 'tagfield',
				fieldLabel: '日期',
				store: store,
				displayField: 'text',
				valueField: 'value',
				queryMode: 'local',
				filterPickList: true,
				labelWidth: 50
			});

			var init_wind = Ext.create('Ext.window.Window', {
				title: '选择需要排序的工厂',
				width: 400,   //Number型，也可以是字符串类型 width:'90%'
				height: 200,
				modal: true,
				items: [
					{
						xtype: 'panel',
						layout: 'form',
						items: [
							{
								fieldLabel: '产线',
								id: 'zd_WIP_ID',
								xtype: 'combobox',
								editable: false,
								labelWidth: 50,
								queryMode: 'local',
								valueField: 'value',
								displayField: 'text',
								store: store2,
								listeners: {
									select: function (combo) {
										var val = combo.getValue();
										DateCbox.store.removeAll();
										DateCbox.setValue('');
										var DateCbox_data = [];
										foreach(res_ary, function (ary) {
											if (ary.Resource_ID == val) {
												foreach(ary.data, function (item) {
													var d = new Date(item.Date).format('yyyy/MM/dd');
													DateCbox_data.push({
														value: d,
														text: d
													});
												});
											}
										});
										store.loadData(DateCbox_data);
										DateCbox.resumeEvents();
									}
								}
							}, DateCbox, {
								fieldLabel: '顺序',
								id: 'zd_asc_desc',
								xtype: 'combobox',
								editable: false,
								labelWidth: 50,
								queryMode: 'local',
								valueField: 'value',
								displayField: 'text',
								value: 1,
								store: Ext.create('Ext.data.Store', {
									fields: ['value', 'text'],
									data: [{ value: 1, text: '正序' }, { value: 0, text: '倒序' }]
								})
							}
						]
					}
				],
				fbar: [
					{
						type: 'button',
						text: '确定',
						handler: function () {
							var WIP_ID = getTop().Ext.getCmp("zd_WIP_ID").getRawValue();
							var ary_date = DateCbox.getRawValue();
							var WorkShopLine = getListWithMultParams("WorkShopLine", { WorkShopId: WIP_ID });
							var work_noid = WorkShopLine.length > 0 ? WorkShopLine[0].Work_Shift : '';
							if (work_noid == null || work_noid == "" || work_noid == undefined) {
								Alert('提示：', WIP_ID + '未设置班制！');
								return false;
							}
							let w_shift = Work_Shift.filter(function (p) {
								if (p.Work_Noid === work_noid) {
									return p;
								}
							});
							let Temp = [];
							foreach(ary_date.split(','), function (ary) {
								foreach(cv, function (p) {
									let d = new Date(p.Date).format('yyyy/MM/dd');
									if (d == ary && p.Resource_ID == WIP_ID) {
										if (p.Number != null && p.Number != "" && p.GcdType == 0) {
											Temp.push(p);
											return p;
										}
									}
								});
							});
							Temp.sort((a, b) => b.SandTypeId.localeCompare(a.SandTypeId));
							Temp = AssessmentOfHours(Temp, w_shift, WIP_ID);
							foreach(Temp, function (el) {
								cv.filter(function (p) {
									if (p.Number == el.Number && p.Lock == 0) {
										p = el;
										return p;
									}
								});
							});
							theGrid.collectionView.refresh();
							init_wind.close();
						}
					},
					{
						type: 'button',
						text: '取消',
						handler: function () {
							init_wind.close();
						}
					}
				]
			});
			init_wind.show();
		}
	});
	/**
	 * 洗机分析
	 * 按照界面上工单的顺序，第一行和第二行按照全览表中切换分类进行判断是否需要洗机，一次类推
	 * */
	let btnWashingMachineAnalysis = Ext.create('Ext.Button', {
		tooltip: '洗机分析',
		glyph: 0xf2cd,
        disabled:true,
		handler: function () {
			//删除洗机工单
			DelEquWash_GD();
			var source = theGrid.collectionView.sourceCollection;
			//var source = theGrid.collectionView.items;
			let xifx_ary = [];
			TblEquWash_ary = [];
			let TblEquWash, temp_data = {};
			for (let i = 0; i < source.length; i++) {
				if (source[i] != undefined) {
					if (source[i].GcdType == 2) {
						source[i].GcdType = 0;
					}
				}
			}
			foreach(source, function (item) {
				temp_data[item.Resource_ID] = source.filter(function (p) {
					if (p.Resource_ID == item.Resource_ID) {
						if (p.GcdType == 4) {
							return;
						}
						return p;
					}
				});
			});

			foreach(temp_data, function (r) {
				r.sort(function (a, b) { return a.index - b.index });
				for (let i = 0; i < r.length; i++) {
					if (i == r.length - 1) {
						break;
					}
					var invid = r[i].Inventory_ID;
					var WipID = r[i].ParentID;
					var TM_invid = r[i + 1].Inventory_ID;
					if (invid != "" && invid != null && TM_invid != "" && TM_invid != null) {
						var inv = AllSettings.filter(function (p) {
							if (p.Inventory_ID == invid && p.WipID == WipID) {
								return p;
							}
						});
						var TM_inv = AllSettings.filter(function (p) {
							if (p.Inventory_ID == TM_invid && p.WipID == WipID) {
								return p;
							}
						});
						var CutClassify = inv.length == 0 ? '' : inv[0].CutClassify;
						var TM_CutClassify = TM_inv.length == 0 ? '' : TM_inv[0].CutClassify;
						TblEquWash = TblEquWashTime.filter(function (p) {
							if (p.FMfgCatID === CutClassify && p.TMfgCatID === TM_CutClassify) {
								return p;
							}
						});
						if (TblEquWash.length > 0) {
							if (TblEquWash[0].UseTimes > 0) {
								xifx_ary.push(r[i]);
								let obj = new Object();
								obj.index = r[i].index;
								obj.ParentID = r[i].ParentID;
								obj.Resource_ID = r[i].Resource_ID;
								obj.Resource_index = r[i].Resource_index;
								obj.Resource = r[i].Resource;
								obj.Date = r[i].Date;
								obj.ScheduleEndDate = r[i].Date;
								obj.Scheduling = r[i].Scheduling;
								obj.GcdType = 3;
								obj.ScheduleDateDifference = 0;
								obj.Inventory_ID = TblEquWash[0].FMfgCatID + '-->' + TblEquWash[0].TMfgCatID;
								obj.PlanDate = TblEquWash[0].UseTimes / 60;
								obj.PlanQty = 0;
								obj.Summary = TblEquWash[0].WashDes;
								obj.SaOrderKey = 0;
								TblEquWash_ary.push(obj);
							}
						}
					}
				}
				foreach(xifx_ary, function (el) {
					source.sort(function (a, b) { return a.index - b.index });
					foreach(source, function (p) {
						if (p.index == el.index) {
							p.GcdType = 2;
							return p;
						}
					});
				});
			});
			console.log(TblEquWash_ary);
			//gridsort();
			theGrid.collectionView.refresh();
			if (TblEquWash_ary.length == 0) {
				Alert('提示：', "无需洗机！");
			} else {
				Alert('提示：', "分析完成！");
			}
		}
	});
	/**
	 * 洗机工单
	 * 将洗机分析出来需要洗机的工单按照顺序插入当前界面
	 * */
	let btnWashingProductionOrder = Ext.create('Ext.Button', {
		tooltip: '洗机工单',
		glyph: 0xf0ea,
		style:"color:black",
        disabled:true,
		handler: function () {
			let source = theGrid.collectionView.sourceCollection;
			let TblEquWash, temp_data = {};
			function getArrayIndex(arr, obj) {
				var i = arr.length;
				while (i--) {
					if (arr[i].Number == obj.Number) {
						return i;
					}
				}
				return -1;
			}
			if (TblEquWash_ary.length > 0) {
				foreach(source, function (item) {
					temp_data[item.Resource_ID] = source.filter(function (p) {
						if (p.Resource_ID == item.Resource_ID) {
							if (p.GcdType == 4) {
								return;
							}
							return p;
						}
					});
				});

				foreach(temp_data, function (r) {
					r.sort(function (a, b) { return a.index - b.index });
					for (let i = 0; i < r.length; i++) {
						if (i == r.length - 1) {
							break;
						}
						var invid = r[i].Inventory_ID;
						var WipID = r[i].ParentID;
						var TM_invid = r[i + 1].Inventory_ID;
						if (invid != "" && invid != null && TM_invid != "" && TM_invid != null) {
							var inv = AllSettings.filter(function (p) {
								if (p.Inventory_ID == invid && p.WipID == WipID) {
									return p;
								}
							});
							var TM_inv = AllSettings.filter(function (p) {
								if (p.Inventory_ID == TM_invid && p.WipID == WipID) {
									return p;
								}
							});
							var CutClassify = inv.length == 0 ? '' : inv[0].CutClassify;
							var TM_CutClassify = TM_inv.length == 0 ? '' : TM_inv[0].CutClassify;
							TblEquWash = TblEquWashTime.filter(function (p) {
								if (p.FMfgCatID === CutClassify && p.TMfgCatID === TM_CutClassify) {
									return p;
								}
							});
							if (TblEquWash.length > 0) {
								if (TblEquWash[0].UseTimes > 0) {
									let obj = new Object();
									obj.index = r[i].index;
									obj.ParentID = r[i].ParentID;
									obj.Resource_ID = r[i].Resource_ID;
									obj.Resource_index = r[i].Resource_index;
									obj.Resource = r[i].Resource;
									obj.Date = r[i].Date;
									obj.Lock = 0;
									obj.ScheduleEndDate = r[i].Date;
									obj.Scheduling = r[i].Scheduling;
									obj.GcdType = 3;
									obj.ScheduleDateDifference = 0;
									obj.Inventory_ID = TblEquWash[0].FMfgCatID + '-->' + TblEquWash[0].TMfgCatID;
									obj.PlanDate = TblEquWash[0].UseTimes / 60;
									obj.PlanQty = 0;
									obj.Summary = TblEquWash[0].WashDes;
									obj.SaOrderKey = 0;
									let _index = getArrayIndex(source, r[i]);
									source.splice(_index + 1, 0, obj);
									theGrid.collectionView.refresh();
								}
							}
						}
					}
				});
				theGrid.collectionView.refresh();
				Alert('提示：', "洗机工单完成！");
			} else {
				Alert('提示：', "请做洗机分析！", null, null, null, null, true);
			}
			TblEquWash_ary = [];
		}
	});
	/**
	 * 优化配置表
	 * 打开洗机工时表
	 * */
	let btnOptimizedConfiguration = Ext.create('Ext.Button', {
		tooltip: '优化配置表',
		glyph: 0xf24e,
        disabled:true,
		handler: function () {
			getTopWindow().openWindow("优化配置表", "/TblEquWashTime?disble_operate_type=Add,Edit,Delete,Print,Record,BackRecord,Verify", 1100, 600, function () { });
		}
	});
	/**
	 * 上移
	 * 将选择的行记录向上移动一行
	 * */
	let btnMoveUpward = Ext.create('Ext.Button', {
		tooltip: '上移',
		glyph: 0xf062,
		listeners: {
			click: {
				buffer: 000,
				fn: function (upbtn) {
					let source = theGrid.collectionView.sourceCollection;
					if (theGrid.selectedItems.length < 1) {
						Alert('提示：', '请选择操作项');
						return false;
					} else {
						upbtn.disable();
						let cv = theGrid.collectionView;
						let rows = theGrid.selectedItems[0];
						let item_index = rows.index;
						let new_item_index = item_index - 1

						if (item_index > 0) {
							if (new_item_index >= 0) {
								theGrid.beginUpdate();
								let item = source[item_index];
								let newitem = source[new_item_index];
								let gcd_type = item.GcdType;

								let old_id = item.index;
								let new_id = newitem.index;

								let old_date = item.Date;
								let new_date = newitem.Date;

								let old_scheduling = item.Scheduling;
								let new_scheduling = newitem.Scheduling;

								let old_scheduleenddate = item.ScheduleEndDate;
								let new_scheduleenddate = newitem.ScheduleEndDate;

								if (gcd_type == 4 && item.Lock == 1) {
									if (new Date(old_date) - new Date(new_date) == 0 && old_scheduling == new_scheduling) {

										item.index = new_id;
										newitem.index = old_id;

										item.Date = new_date;
										newitem.Date = old_date;

										item.Scheduling = new_scheduling;
										newitem.Scheduling = old_scheduling;

										item.ScheduleEndDate = new_scheduleenddate;
										newitem.ScheduleEndDate = old_scheduleenddate;
									} else {
										alert('不能移除固定范围！');
									}
								} else {

									item.index = new_id;
									newitem.index = old_id;

									item.Date = new_date;
									newitem.Date = old_date;

									item.Scheduling = new_scheduling;
									newitem.Scheduling = old_scheduling;

									item.ScheduleEndDate = new_scheduleenddate;
									newitem.ScheduleEndDate = old_scheduleenddate;
								}
								cv.refresh();
								theGrid.endUpdate();
							}
						}
					}
				}
			}
		}
	});
	/**
	 * 下移
	 * 将选中的行记录向下移动一行
	 * */
	let btnMoveDown = Ext.create('Ext.Button', {
		tooltip: '下移',
		glyph: 0xf063,
		listeners: {
			click: {
				buffer: 000,
				fn: function (downbtn) {
					let source = theGrid.collectionView.sourceCollection;

					if (theGrid.selectedItems.length < 1) {
						Alert('提示：', '请选择操作项');
						return false;
					} else {
						downbtn.disable();
						let cv = theGrid.collectionView;
						let rows = theGrid.selectedItems[0];
						let item_index = rows.index;
						let new_item_index = item_index + 1
						if (item_index < source.length) {
							if (new_item_index < source.length) {
								theGrid.beginUpdate();
								let item = source[item_index];
								let newitem = source[new_item_index];
								let gcd_type = item.GcdType;

								let old_id = item.index;
								let new_id = newitem.index;

								let old_date = item.Date;
								let new_date = newitem.Date;

								let old_scheduling = item.Scheduling;
								let new_scheduling = newitem.Scheduling;

								let old_scheduleenddate = item.ScheduleEndDate;
								let new_scheduleenddate = newitem.ScheduleEndDate;

								if (gcd_type == 4 && item.Lock == 1) {
									if (new Date(old_date) - new Date(new_date) == 0 && old_scheduling == new_scheduling) {

										item.index = new_id;
										newitem.index = old_id;

										item.Date = new_date;
										newitem.Date = old_date;

										item.Scheduling = new_scheduling;
										newitem.Scheduling = old_scheduling;

										item.ScheduleEndDate = new_scheduleenddate;
										newitem.ScheduleEndDate = old_scheduleenddate;
									} else {
										alert('不能移除固定范围！');
									}
								} else {

									item.index = new_id;
									newitem.index = old_id;

									item.Date = new_date;
									newitem.Date = old_date;

									item.Scheduling = new_scheduling;
									newitem.Scheduling = old_scheduling;

									item.ScheduleEndDate = new_scheduleenddate;
									newitem.ScheduleEndDate = old_scheduleenddate;
								}
								cv.refresh();
								theGrid.endUpdate();
							}
						}
					}
				}
			}
		}
	});
	/**
	 * 自动排序
	 * 根据产线日产能、白班、夜班的产能，将每个一个产线下所有工单进行产能分摊
	 * */
	let btnAutomaticSorting = Ext.create('Ext.Button', {
		tooltip: '自动排序',
		glyph: 0xf25b,
		handler: function () {
			var res_ary = {};
			var source = theGrid.itemsSource.items;
			var store2 = Ext.create('Ext.data.Store', {
				fields: ['value', 'text'],
				data: []
			});
			//删除洗机工单
			DelEquWash_GD();
			foreach(source, function (item) {
				if (res_ary[item.Resource_ID] == null) {
					res_ary[item.Resource_ID] = 1;
					store2.addSorted({
						value: item.Resource_ID,
						text: item.Resource
					});
				}
			});
			var init_wind = Ext.create('Ext.window.Window', {
				title: '选择需要排序的工厂',
				width: 300,   //Number型，也可以是字符串类型 width:'90%'
				height: 200,
				modal: true,
				items: [
					{
						xtype: 'panel',
						layout: 'form',
						items: [
							{
								fieldLabel: '产线',
								id: 'zd_WIP_ID',
								xtype: 'combobox',
								editable: false,
								queryMode: 'local',
								valueField: 'value',
								displayField: 'text',
								store: store2
							}
						]
					}
				],
				fbar: [
					{
						type: 'button',
						text: '确定',
						handler: function () {
							var WIP_ID = getTop().Ext.getCmp("zd_WIP_ID").getRawValue();
							var WorkShopLine = getListWithMultParams("WorkShopLine", { WorkShopId: WIP_ID });

							var work_noid = WorkShopLine.length > 0 ? WorkShopLine[0].Work_Shift : '';
							if (work_noid == null || work_noid == "" || work_noid == undefined) {
								Alert('提示：', WIP_ID + '未设置班制！');
								return false;
							}

							let w_shift = Work_Shift.filter(function (p) {
								if (p.Work_Noid === work_noid) {
									return p;
								}
							});
							let Temp = [];
							foreach(source, function (p) {
								Temp.push(p)
							})

							theGrid.beginUpdate();
							Temp = Temp.sort(function (a, b) { return a.index - b.index });
							foreach(AssessmentOfHours(Temp, w_shift, WIP_ID), function (el) {
								for (let i = 0; i < source.length; i++) {
									if (source[i].Number == el.Number && source[i].Lock == 0) {
										source[i] = el;
									}
								};
							});
							theGrid.endUpdate();
							theGrid.itemsSource.refresh();

							init_wind.close();
							theGrid.collapseGroupsToLevel(2);
						}
					},
					{
						type: 'button',
						text: '取消',
						handler: function () {
							init_wind.close();
						}
					}
				]
			});
			init_wind.show();
		}
	});
	/**
	 * 保存
	 * 将当前界面的工单数据保存到排产计划表中
	 * */
	let btnSave = Ext.create('Ext.Button', {
		tooltip: '保存',
		glyph: 0xf0c7,
		handler: function () {
			var source = theGrid.collectionView.sourceCollection;
			//计划主表：ProductionPlanGcd
			// 设置要打开窗口的地址，打开的表用编码表示，此处打开订单表（以创建模式打开）
			var url = "/ProductionPlanGcd/edit?createmode=true";

			// 将查询字符串固定的参数添加到url中，每次打开的窗口都有一些固定的参数存在，如制定数据库编号
			var urlarg = new Array();

			foreach(__fq, function (v, i, leave, name) { urlarg.push(name + "=" + encodeURIComponent(v)); });

			url += "&" + urlarg.join("&");

			// 打开编辑对话框，函数定义见main.js
			parent.openWindow("工单粗排计划", url, 900, 600,
				function () { }, 0xf067,
				// openWindow 的参数initwnd，当窗口打开后执行，设置窗口界面加载完成所执行的函数
				function (newwnd) {
					var childFrame = newwnd.getChildFrame('ProductionPlanGcdDetail');
					Wait.Start(null, "正在执行操作，请稍候.....");
					setTimeout(() => {
						source.sort(function (a, b) { a.index - b.index });
						foreach(source, function (v, i) {
							if (v.GcdType >= 0) {
								var def = Math.round((new Date(v.PlanDateEnd) - new Date(v.ScheduleEndDate)) / 1000 / 60 / 60 / 24);
								var obj = new Object();
								obj.WIP_ID = v.ParentID;
								obj.Noid = i;
								obj.CreateDate = v.Date;
								obj.Resource_index = v.Resource_index;
								obj.Scheduling = v.Scheduling;
								obj.IssuleNo = v.Number;
								obj.ScheduleStartDate = v.ScheduleStartDate;
								obj.ScheduleEndDate = v.ScheduleEndDate;
								obj.ScheduleDateDifference = def;
								obj.CustomerKey = v.SaOrderKey;//.substring(s.lastIndexOf("/") + 1);
								obj.BatchNO = v.BatchNO;
								obj.PlanNpkg = v.PlanNpkg;
								obj.Lock = v.Lock;
								obj.StdInventory_ID = v.StdInventory_ID;
								obj.MfgCatID = v.MfgCatID;
								obj.Unit_Weight = v.Unit_Weight;
								obj.HCapacity = v.HCapacity;
								obj.Summary = v.Summary;
								obj.Matching = v.Matching;
								obj.Resource_ID = v.Resource_ID;
								obj.Inventory_id = v.Inventory_ID;
								obj.PbeginDate = v.PlanDateStart;
								obj.PEndDate = v.PlanDateEnd;
								obj.MfgPlanTime = v.PlanDate;
								obj.IssueQty = v.PlanQty;
								obj.ProQty = v.PlanQty;
								childFrame.addChildRow(obj);
							}
						});
						newwnd.setPropertyValue(null, 'Type', 2);
						newwnd.setPropertyValue(null, 'WIP_ID', source[0].ParentID);
						Wait.hide();
					}, 1000);
				}, null, isjsschema);
		}
	});
	/**
	 * 编辑虚拟工单
	 * 修改选择中的虚拟工单
	 * */
	let btnVirtualTicketEdit = new Ext.Button({
		tooltip: '编辑虚拟工单',
		text: '虚',
		hidden: false,
		glyph: 0xf14b,
		handler: function () {
			let cv = theGrid.itemsSource;
			let row = cv.currentItem;
			if (row.GcdType == 4) {
				let Gcd_No = row.Number.match(/(\S*)-/)[1];
				let source = theGrid.collectionView.sourceCollection;
				let gd_status = getListWithMultParams("TblVirtualTicket", { EvidenceNumber: '=' + Gcd_No });
				if (Gcd_No == null || Gcd_No == "" || Gcd_No == undefined) {
					Alert('提示：', '请选择需要修改的虚拟工单！');
					return false;
				} else if (gd_status[0].Verify == 1) {
					Alert('提示：', '该工单已审核，无法编辑！');
					return false;
				} else {
					getTopWindow().openWindow("虚拟工单", "/TblVirtualTicket/edit?editmode=true&EvidenceNumber=" + Gcd_No, 900, 600, function (v) {
						if (v != null && v[0].success == true) {
							let child_list = getListWithMultParams("TblVirtualTicketDetails", { EvidenceNumber: v[1].EvidenceNumber });
							foreach(child_list, function (el, i) {
								i = i + 1;
								var temp = WorkShopLine.filter(function (p) {
									if (v[1].ProductionLine == p.Code_ID) {
										return p;
									}
								});
								var desc = LocaltblItem.filter(function (p) {
									return p.FCode === el.Shift;
								});
								var desc = source.filter(function (p) {
									if (p.Number === el.EvidenceNumber + '-' + el.NOID) {
										p.Resource_ID = temp.length > 0 ? temp[0].Description : '';
										p.Resource = temp.length > 0 ? temp[0].Description : '';
										p.Resource_index = 1;
										p.ParentID = v[1].Factory;
										p.Date = getTop().wijmo.Globalize.parseDate(el.Date, 'yyyy/MM/dd');
										p.PlanDateStart = getTop().wijmo.Globalize.parseDate(el.Date, 'yyyy/MM/dd');
										switch (el.Shift) {
											case "白班":
												p.Scheduling = '001';
												break;
											case "夜班":
												p.Scheduling = '002';
												break;
											case "早班":
												p.Scheduling = '003';
												break;
											case "晚班":
												p.Scheduling = '004';
												break;
											default: p.Scheduling = el.Shift;
										}
										p.Inventory_ID = '虚拟工单';
										p.Lock = 1;
										p.Number = el.EvidenceNumber + '-' + el.NOID;
										p.PlanQty = el.VirtualCapacity;
										p.PlanDate = el.VirtualWork;
										p.ScheduleStartDate = getTop().wijmo.Globalize.parseDate(el.Date, 'yyyy/MM/dd');
										p.ScheduleEndDate = getTop().wijmo.Globalize.parseDate(el.Date, 'yyyy/MM/dd');
										p.Summary != null && el.Reason != "" ? el.Reason + ':' + v[1].Summary : v[1].Summary;
										p.GcdType = 4;
									}
								});
							});
							theGrid.collectionView.refresh();
						}
					});
				}
			} else {
				Alert('提示：', '请选择虚拟工单！');
				return false;
			}

		}
	});
	/**
	 * 读取虚拟工单
	 * 选择需要插入的虚拟工单数据插入到当前排产界面
	 * */
	let btnVirtualTicketRead = new Ext.Button({
		tooltip: '读取虚拟工单',
		text: '虚',
		hidden: false,
		glyph: 0xf518,
		handler: function () {
			let source = theGrid.collectionView.sourceCollection;
			let gd_arry = [];
			var cond = { t: "and", child: [] };
			foreach(source, function (item) {
				if (item.GcdType == 4) {
					gd_arry.push(item.Number.match(/(\S*)-/)[1]);
				}
			});

			gd_arry = gd_arry.distinct();
			let gcd = gd_arry.join(';');
			let con_ary = [
				{ c: "EvidenceNumber", cp: 'notin', v: gcd },
				{ c: "Verify", cp: '=', v: 1 }
			];
			cond.child = con_ary;
			function wnd(list) {
				foreach(list, function (el) {
					var work = WorkShopLine.filter(function (p) {
						if (p.Code_ID == el.Factory) {
							return p;
						}
					});
					var line = WorkShopLine.filter(function (p) {
						if (p.Code_ID == el.ProductionLine) {
							return p;
						}
					});
					el.Factory_name = work.length == 0 ? "" : work[0].Description;
					el.ProductionLine_name = line.length == 0 ? "" : line[0].Description;
				});
				var store = Ext.create('Ext.data.Store', {
					fields: ['EvidenceNumber', 'Factory', 'Factory_name', 'ProductionLine', 'ProductionLine_name', 'BeginDate', 'EndDate', 'Maker', 'SumWrkHour', 'SumCapacity', 'Reason', 'Summary'],
					data: list
				});
				var grid = getTop().Ext.create('Ext.grid.Panel', {
					store: store,
					region: 'south',
					frame: false,
					width: 900,
					height: '100%',
					viewConfig: {
						columnLines: true,
						stripeRows: true,
						enableTextSelection: true,
						animateShadow: true,
						forceFit: true
					},
					selModel: {
						mode: 'Single',
						checkboxSelect: true,
						injectCheckbox: 1,
						type: 'checkboxmodel'
					},
					columns: [
						{ header: '', xtype: 'rownumberer', width: 45, align: 'center', sortable: false, menuDisabled: true },
						{
							dataIndex: 'EvidenceNumber', header: '工单号', width: 120, sortable: false, menuDisabled: true
						},
						{ dataIndex: 'Factory', header: '工厂', hidden: true, width: 109, sortable: false, menuDisabled: true },
						{ dataIndex: 'Factory_name', header: '工厂', width: 109, sortable: false, menuDisabled: true },
						{
							dataIndex: 'ProductionLine', header: '产线', hidden: true, width: 87, sortable: false, menuDisabled: true
						},
						{ dataIndex: 'ProductionLine_name', header: '产线', width: 109, sortable: false, menuDisabled: true },
						{ dataIndex: 'BeginDate', header: '开始日期', width: 112, sortable: false, menuDisabled: true },
						{ dataIndex: 'EndDate', header: '截止日期', width: 112, sortable: false, menuDisabled: true },
						{ dataIndex: 'SumWrkHour', header: '总虚拟工时', width: 74, sortable: false, menuDisabled: true },
						{ dataIndex: 'SumCapacity', header: '总虚拟产能', width: 61, sortable: false, menuDisabled: true },
						{ dataIndex: 'Reason', header: '原因', width: 100, sortable: false, menuDisabled: true },
						{ dataIndex: 'Summary', header: '备注', width: 74, sortable: false, menuDisabled: true },
						{ dataIndex: 'Maker', header: '制单人', width: 200, sortable: false, menuDisabled: true },
					]
				});
				var init_wind = getTop().Ext.create('Ext.window.Window', {
					title: '虚拟工程单',
					width: 830,
					height: 480,
					modal: true,
					maximizable: true,
					items: [grid],
					listeners: {
						resize: function (wn, width, height) {
							let grid = wn.items.items[0];
							grid.setHeight(height - 80);
							grid.setWidth(width - 15);
						}
					},
					fbar: [
						{
							type: 'button',
							text: '选择',
							handler: function () {
								let selectrows = grid.getSelectionModel().getSelection();
								if (selectrows.length > 0) {
									let selectrow = selectrows[0].data;
									let child_list = getListWithMultParams("TblVirtualTicketDetails", { EvidenceNumber: selectrow.EvidenceNumber });
									foreach(child_list, function (item, i) {
										i = i + 1;
										let view = theGrid.collectionView;
										let newItem = view.addNew();
										var temp = WorkShopLine.filter(function (p) {
											if (selectrow.ProductionLine == p.Code_ID) {
												return p;
											}
										});
										newItem.Resource_ID = temp.length > 0 ? temp[0].Description : '';
										newItem.Resource = temp.length > 0 ? temp[0].Description : '';
										newItem.Resource_index = 1;
										newItem.ParentID = selectrow.Factory;
										newItem.Date = getTop().wijmo.Globalize.parseDate(item.Date, 'yyyy/MM/dd');
										newItem.PlanDateStart = getTop().wijmo.Globalize.parseDate(item.Date, 'yyyy/MM/dd');
										//newItem.Scheduling = desc.length > 0 ? desc[0].FDescript : '';;
										switch (item.Shift) {
											case "白班":
												newItem.Scheduling = '001';
												break;
											case "夜班":
												newItem.Scheduling = '002';
												break;
											case "早班":
												newItem.Scheduling = '003';
												break;
											case "晚班":
												newItem.Scheduling = '004';
												break;
											default: newItem.Scheduling = item.Shift;
										}
										newItem.Lock = 1;
										newItem.Inventory_ID = '虚拟工单';
										newItem.Number = item.EvidenceNumber + '-' + item.NOID;
										newItem.PlanQty = item.VirtualCapacity;
										newItem.PlanDate = item.VirtualWork;
										newItem.ScheduleStartDate = getTop().wijmo.Globalize.parseDate(item.Date, 'yyyy/MM/dd');
										newItem.ScheduleEndDate = getTop().wijmo.Globalize.parseDate(item.Date, 'yyyy/MM/dd');
										newItem.GcdType = 4;
										newItem.Summary = item.Reason != null && item.Reason != "" ? item.Reason + ':' + selectrow.Summary : selectrow.Summary;
										view.commitNew();
									});
									theGrid.collectionView.refresh();
									init_wind.close();
									return true;
								} else {
									Alert('提示：', '请选择数据！');
									return false;
								}
							}
						}, {
							type: 'button',
							text: '取消',
							handler: function () {
								init_wind.close();
							}
						}
					]
				});
				init_wind.show();
			}
			Wait.Start(null, "正在执行操作，请稍候.....");
			list = getListWithMultParams("TblVirtualTicket", { _cdt: jsonEncode(cond) },
				null, {
				callback: function (vitems) {
					Wait.hide();
					wnd(vitems);
				},
				async: function () {

				}
			});
		}
	});

	/**
	 * 查看全览表
	 * 打开全览表数据
	 * */
	let btnViewOverview = Ext.create('Ext.Button', {
		tooltip: '查看全览表',
		glyph: 0xf15c,
		handler: function () {
			let cv = theGrid.itemsSource;
			let invid;
			if (cv.currentItem == null || cv.currentItem == '' || cv.currentItem == undefined) {
				Alert('提示：', '请选择需要查询的物料！');
				return false;
			} else {
				invid = cv.currentItem.Inventory_ID
				getTopWindow().openWindow("全览表", "/AllSettings?disble_operate_type=Add,Edit,Delete,Print,Record,BackRecord,Verify&Inventory_ID=" + invid
					, 1100, 600, function () { });
			}
		}
	});

	/**
	 * 导出Excel
	 * 将当前界面的排产数据导出到Excel文件中
	 * */
	let btnExportExcel = Ext.create('Ext.Button', {
		tooltip: '导出Excel',
		glyph: 0xf1c3,
		handler: function () {
			Wait.Start(null, "正在执行操作，请稍候.....");
			setTimeout(() => {
				theGrid.collapseGroupsToLevel(3);
				getTop().wijmo.grid.xlsx.FlexGridXlsxConverter.saveAsync(theGrid, { includeColumnHeaders: true }, '工单粗排.xlsx');
				theGrid.collapseGroupsToLevel(2);
				Wait.hide();
			}, 500);
		}
	});
	/**
	 * 删除
	 * 将选择的行记录数据从当前排产界面中移除
	 * */
	let btnDelete = Ext.create('Ext.Button', {
		tooltip: '删除',
		glyph: 0xf2ed,
		handler: function () {
			Confirm('提示：', '确定删除？', function () {
				var cv = theGrid.itemsSource;
				cv.remove(cv.currentItem);
				cv.refresh();
			}, null, null);
		}
	});
	/**
	 * 初始化数据
	 * 按工厂、产线、日期进行数据初始化
	 * */
	let btnInitializationData = Ext.create('Ext.Button', {
		tooltip: '初始化数据',
		glyph: 0xf00a,
		handler: function () {
			var source = theGrid.collectionView.sourceCollection;
			var view = theGrid.collectionView;
			var CxCbox = new Ext.form.field.Tag({
				xtype: 'tagfield',
				fieldLabel: '产线',
				store: new Ext.create('Ext.data.Store', {
					fields: ['value', 'text'],
					data: []
				}),
				displayField: 'text',
				valueField: 'value',
				queryMode: 'local',
				filterPickList: true,
				labelWidth: 50
			});
			var init_wind = Ext.create('Ext.window.Window', {
				title: '初始化数据',
				width: 400,   //Number型，也可以是字符串类型 width:'90%'
				height: 300,
				modal: true,
				items: [
					{
						xtype: 'panel',
						layout: 'form',
						items: [
							{
								fieldLabel: '车间',
								id: 'WIP_ID',
								xtype: 'combobox',
								editable: false,
								queryMode: 'local',
								valueField: 'value__',
								displayField: 'TheNameValue',
								store: getTop().newJsonStore({
									fields: ['value__', 'TheNameValue'],
									data: [
										{ "value__": "", "TheNameValue": "[无]" },
										{ "value__": "WIP_ID", "TheNameValue": "[浏览]" },
									]
								}),
								listeners: {
									afterRender: function (combo) {
										combo.setValue(combo.getStore().getAt(0).get("value__"));//同时下拉框会将与name为firstValue值对应的 text显示
									},
									select: function (combo) {
										var c1 = combo.getValue();
										var pagesize = "&ps=" + 500;  //定义每页记录的条数,可把 parent.selectmodePagesize改为数字.
										var val;
										var url = "/WorkShopLine?disble_operate_type=Add,Edit,Delete,Search&selectmode=true{0}&Type=1,2".format(pagesize, 1);
										if (c1 == "WIP_ID") {
											combo.setValue(combo.getStore().getAt(0).get("value__"));
											getTop().openWindow("车间档案", url, 800, 600, function (v) {
												if (v != null && typeof (v) == "object") {
													if (v.length > 1) {
														if (v[0].success == 'true' || v[0].success == true) {
															foreach(v, function (vitem) {
																val = vitem.Code_ID;
                                                                CreateDataMap([{id:vitem.Code_ID,name:vitem.Description}], "ParentID");
															});
                                                            
															var flg = 0;
															for (var i = 0; i < combo.getStore().getCount(); i++) {
																var recored = combo.getStore().getAt(i).get("value__");
																if (recored == val) {
																	flg++;
																}
															}
															if (flg == 0) {
																combo.getStore().add({ value__: val, TheNameValue: val });
															}
															combo.setValue(val);
															let shopline_ary = WorkShopLine.filter(function (p) {
																if (p.Parent_ID == val) {
																	return p;
																}
															});
															var cxCbox_data = [];
															foreach(shopline_ary, function (item) {
																cxCbox_data.push({
																	value: item.Code_ID,
																	text: item.Description
																});
															});
															CxCbox.getStore().loadData(cxCbox_data);
															CxCbox.resumeEvents();
														}
													}
												}
											}, "", null, null, isjsschema);
										}
									}
								}
							}, CxCbox,
							{
								fieldLabel: '排产天数',
								id: 'pc_days',
								name: 'pc_days',
								value: 1,
								xtype: 'numberfield',
								AllowNegative: false,
								minValue: 0,
								maxValue: 100,
								listeners: {
									change: function (field, value) {
										if (value == 0 || value < 0) {
											field.setValue(1);
										}
									}
								}
							}
						]
					}
				],
				fbar: [
					{
						type: 'button',
						text: '确定',
						handler: function () {
							var pc_days = getTop().Ext.getCmp("pc_days").getRawValue();
							//var Resource_ID = getTop().Ext.getCmp("Resource_ID").getRawValue();
							let cxval_ary = CxCbox.getRawValue();
							let cxtext_ary = CxCbox.getValue();
							let cx_ary = [];
							debugger
							foreach(CxCbox.getValueRecords(), function (row) {
								cx_ary.push({
									value: row.get('value'),
									text: row.get("text"),
								});
							});
							if (cxtext_ary.length == 0) {
								Alert('提示：', '请选择产线');
								return false;
							}
							if (pc_days == 0 || pc_days < 0) {
								Alert('提示：', '请填写正确的排产天数');
								return false;
							}
							var WIP_ID = getTop().Ext.getCmp("WIP_ID").getRawValue();
							Confirm('提示：', '确定初始化？', function () {
								source.splice(0, source.length);
								theGrid.collectionView.refresh();
								foreach(cx_ary, function (item, j) {
									var temp_date = new Date().format('yyyy/MM/dd');
									ResourceIndex.push({
										Resource_ID: item.value,
										Index: j
									});
									for (var i = 0; i < pc_days; i++) {
										var newItem = view.addNew();
										newItem.ParentID = WIP_ID;
										newItem.GcdType = -1;
										newItem.Date = getTop().wijmo.Globalize.parseDate(new Date(temp_date).format('yyyy/MM/dd'), 'yyyy/MM/dd');
										newItem.Resource_index = j;
										newItem.Resource_ID = item.value;
										newItem.Resource = item.text;
										newItem.Number = '';
										newItem.Scheduling = '001';
										newItem.Inventory_ID = '';
										newItem.Description = '';
										newItem.BatchNO = '';
										newItem.PlanQty = 0;
										newItem.Lock = 0;
										newItem.PlanDateStart = getTop().wijmo.Globalize.parseDate(new Date(temp_date).format('yyyy/MM/dd'), 'yyyy/MM/dd');
										newItem.PlanDate = 0;
										newItem.MfgCatID = '';
										newItem.SandTypeId = '';
										newItem.SaOrderKey = 0;
										newItem.FStatus = '';
										newItem.Capacity = 0;
										newItem.OnePlanMAX = '';
										newItem.StdInventory_ID = '';
										newItem.PlanDateEnd = '';
										newItem.Matching = '';
										newItem.Style = '';
										newItem.Capacity = 0;
										newItem.ScheduleStartDate = getTop().wijmo.Globalize.parseDate(new Date(temp_date).format('yyyy/MM/dd'), 'yyyy/MM/dd');
										newItem.ScheduleEndDate = getTop().wijmo.Globalize.parseDate(new Date(temp_date).format('yyyy/MM/dd'), 'yyyy/MM/dd');
										view.commitNew();
										temp_date = addDate(temp_date, 1);
									}
								});
								let pid = WIP_ID;
								let ary1 = [];
								foreach(WorkShopLine, function (el) {
									if (el.Parent_ID == pid) {
										let obj = new Object();
										obj.id = el.Description;
										obj.name = el.Description;
										ary1.push(obj);
									}
								});
								init_wind.close();
								theGrid.collectionView.refresh();
								theGrid.collapseGroupsToLevel(2);
								CreateDataMap(ary1, "Resource");
							}, function () { }, null);
						}
					},
					{
						type: 'button',
						text: '取消',
						handler: function () {
							init_wind.close();
						}
					}
				]
			});
			init_wind.show();
		}
	});
	/**
	 * 刷新工厂日历、班制、班次、全览表、洗机工单、车间档案、生产工单数据
	 * */
	let btnRefreshData = Ext.create('Ext.Button', {
		tooltip: '刷新工厂日历、班制、班次、全览表、洗机工单、车间档案、生产工单数据',
		glyph: 0xf021,
		handler: function () {
			Wait.Start(null, "数据同步中.....");
			setTimeout(() => {
				sourceData();
				Wait.hide();
			}, 1000);
			Alert('提示：', '档案数据刷新完成');
		}
	});
	/**
	 * 锁定工单
	 * 按产线、日期、班次进行批量锁定工单
	 **/
	let btnLockTicket = Ext.create('Ext.Button', {
		tooltip: '按产线、日期、班次进行批量锁定工单',
		glyph: 0xf023,
		handler: function () {
			let source = theGrid.itemsSource.items;
			let resourceStore = Ext.create('Ext.data.Store', {
				fields: ['value', 'text'],
				data: []
			});
			let schedulingStore = Ext.create('Ext.data.Store', {
				fields: ['value', 'text'],
				data: []
			});
			let dateStore = Ext.create('Ext.data.Store', {
				fields: ['value', 'text'],
				data: []
			});
			let resourceCombox = Ext.create('Ext.form.ComboBox', {
				store: resourceStore,
				queryMode: 'local',
				displayField: 'text',
				valueField: 'value',
				editable: false,
			});
			let dateField = {
				xtype: 'datefield',
				anchor: '100%',
				name: 'date',
				format: "Y/m/d",
				value: new Date()  // defaults to today
			}
			let schedulingCombox = Ext.create('Ext.form.ComboBox', {
				store: schedulingStore,
				queryMode: 'local',
				displayField: 'text',
				editable: false,
				valueField: 'value'
			});
			let res_ary;
			res_ary = JsonArrayGroup(source);

			foreach(res_ary, function (item) {
				resourceStore.addSorted({
					value: item.Resource_ID,
					text: item.Resource
				});
			});
			foreach(LocaltblItem, function (el) {
				schedulingStore.addSorted({
					value: el.FCode,
					text: el.FDescript
				});
			});
			schedulingCombox.resumeEvents();
			let lockGrid = getTop().Ext.create('Ext.grid.Panel', {
				store: lockStore,
				region: 'south',
				frame: false,
				width: 900,
				height: '100%',
				viewConfig: {
					columnLines: true,
					stripeRows: true,
					enableTextSelection: true,
					animateShadow: true,
					forceFit: true
				},
				selModel: {
					mode: 'MULTI',
					checkboxSelect: true,
					injectCheckbox: 1,
					type: 'checkboxmodel'
				},
				plugins: {
					ptype: 'cellediting',
					clicksToEdit: 1
				},
				columns: [
					{
						header: '', xtype: 'rownumberer', width: 45, align: 'center', sortable: false, menuDisabled: true
					},
					{
						dataIndex: 'Resource_ID', header: '产线', width: 170, sortable: false, menuDisabled: true, editor: {
							completeOnEnter: false, field: resourceCombox
						}
					},
					{
						dataIndex: 'Date', header: '日期', width: 120, sortable: false, menuDisabled: true,
						completeOnEnter: false, field: dateField, renderer: function (value) {
							return value.format('yyyy/MM/dd');
						}
					},
					{
						dataIndex: 'Scheduling', header: '班次', width: 120, sortable: false, menuDisabled: true,
						completeOnEnter: false, field: schedulingCombox,
						renderer: function (value) {
							let desc = LocaltblItem.filter(function (p) {
								return p.FCode === value;
							});
							return desc.length == 0 ? '' : desc[0].FDescript;
						}
					}, {
						dataIndex: 'Lock', header: '锁定', width: 70, sortable: false, menuDisabled: true,
						completeOnEnter: false,
						field: Ext.create('Ext.form.ComboBox', {
							store: Ext.create('Ext.data.Store', {
								fields: ['value', 'text'],
								data: [{ value: 1, text: '已锁' }, { value: 0, text: '未锁' }]
							}),
							queryMode: 'local',
							displayField: 'text',
							editable: false,
							valueField: 'value',
							value: 0
						}),
						renderer: function (value) {
							return value == 1 ? '已锁' : '未锁';
						}
					}
				],
				tbar: [
					{
						text: '新增',
						glyph: 0xf067,
						handler: function () {
							let obj = new Object()
							obj.Resource_ID = '';
							obj.Date = new Date();
							obj.Scheduling = '';
							obj.Lock = 1;
							lockStore.add(obj);
						}
					},
					{
						text: '删除',
						glyph: 0xf2ed,
						handler: function () {
							let rows = lockGrid.getSelection();
							if (rows.length > 0) {
								foreach(rows, function (rec) {
									lockStore.remove(rec);
								})
							} else {
								Alert('提示：', '请选择需要操作的数据');
								return false;
							}
						}
					}
				]
			});
			var init_wind = Ext.create('Ext.window.Window', {
				title: '锁定工单',
				width: 600,
				height: '90%',
				modal: true,
				items: [lockGrid],
				fbar: [
					{
						type: 'button',
						text: '锁定',
						glyph: 0xf0c7,
						handler: function () {
							LockGcd(source);
							init_wind.close();
							let temp = [];
							theGrid.beginUpdate();
							foreach(lockStore.getData().items, function (el) {
								let item = el.data;
								if (item.Resource_ID == "" || item.Date == "" || item.Scheduling == "") {
									let row = item.id;
									var j = row.substring(row.indexOf('-') + 1, row.length);
									Alert('提示：', "第" + j + "行有空数据");
									return false;
								} else {
									let filter = {
										Resource_ID: [item.Resource_ID],
										Date: [item.Date],
										Scheduling: [item.Scheduling],
									}
									let _row = filterData(temp, filter);
									if (_row.length > 0) {
										Alert('提示：', "不能有重复数据");
										return false;
									} else {
										temp.push({
											Resource_ID: item.Resource_ID,
											Date: item.Date,
											Scheduling: item.Scheduling,
										});


										foreach(source, function (el) {
											var d = new Date(el.Date).format('yyyy/MM/dd');
											if (el.Resource_ID == item.Resource_ID && d == item.Date.format('yyyy/MM/dd') && el.Scheduling == item.Scheduling) {
												el.Lock = item.Lock;
											}
										});


									}
								}
							});
							theGrid.endUpdate();
							init_wind.close();
							theGrid.itemsSource.refresh();
						}
					},
					{
						type: 'button',
						text: '取消',
						glyph: 0xf410,
						handler: function () {
							init_wind.close();
						}
					}
				]
			});
			init_wind.show();
		}
	});
	var tool = [
		btnReadOldPlan, btnReadNowPlan, btnNotFinishProductionOrder, btnBundleAnalysis,
		btnViewGdItemShortage, btnViewGdListShortage, btnAutomaticSorting, btnOptimizedConfiguration,
		btnMoveUpward, btnMoveDown, btnSandSorting, btnWashingMachineAnalysis, btnWashingProductionOrder, btnSave,
		btnVirtualTicketEdit, btnVirtualTicketRead, '->',
		btnLockTicket, btnViewOverview, btnExportExcel, btnDelete, btnInitializationData, btnRefreshData
	];
	return {
		xtype: 'panel',
		layout: 'border',
		tbar: tool,
		items: [
			{
				region: 'center',
				xtype: 'component',
				height: '100%',
				id: id,
				border: false,
				title: false,
				onRender: function () {
				},
				afterRender: function () {
				}
			}
		]
	};
}
